The sliding window technique solves many contiguous subarray and substring problems by updating a range’s state as its boundaries move, instead of recalculating every range from scratch. Use a fixed-width window when the length is given; use a variable-width window when a constraint determines how far the range can grow or must shrink. The key test is whether the problem’s condition supports that movement.
What is a sliding window?
A window is a contiguous range in an array or string, bounded by left and right indices. As the right edge advances, the entering item is added to the state you maintain. If the left edge advances, the departing item is removed. The state might be a sum, a character-frequency table, or a data structure that tracks an extreme value.
As an Amazon Associate I earn from qualifying purchases.
This avoids recomputing overlapping ranges when their state can be updated more cheaply than it can be rebuilt. The usual linear-time guarantee is amortized: if both pointers only move forward, each item enters at most once and leaves at most once. With constant-time updates, the total work is O(n), even when the code contains a nested while loop.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →This pattern is specifically for contiguous ranges. A two-pointer method that starts at opposite ends and moves inward is related, but it is not the same window pattern.
#1 Best Overall
Choose between fixed and variable windows
| Pattern | When to use it | How the boundaries move | Typical state and cost |
|---|---|---|---|
| Fixed width | The range length, such as k, is specified. |
Both boundaries advance together by one position per shift. | A running sum supports constant-time updates. Extrema need a monotone deque; medians generally require ordered state and O(log k) updates. |
| Variable width | The goal is a longest or shortest contiguous range satisfying a condition. | Advance the right edge to include items; move the left edge as needed to restore validity. | State depends on the condition: for example, a sum, frequency counts, or last-seen positions. Cost depends on how that state is updated. |
How to solve a fixed-width window problem
Example: maximum sum of k consecutive elements
Recomputing the sum of every length-k range takes O(k) work per range, or O(nk) overall. A rolling sum takes constant time per shift.
- Decide the required behavior when
kis not a valid width for the input. Reject it, return a designated result, or follow the problem’s stated rules. - Compute the sum of the first complete window and use it to initialize the best sum.
- For each next position, update the sum with
new_sum = old_sum + entering_value - leaving_value. - Compare each updated sum with the best value, or emit the value if the task asks for every window’s sum.
For example, with values [2, 5, 1, 3] and k = 3, the first sum is 8. The next window adds 3 and removes 2, giving 9. Only the entering and departing values need to be processed for that shift.
Rank #2
- color: White
- INTRODUCTION TO ALGORITHMS, FOURTH EDITION
When the fixed-width state is not a sum
A running sum cannot by itself maintain a rolling maximum or minimum: the outgoing item may have been the previous extreme. A monotone deque of candidate indices supports fixed-window extrema in linear total time. For a median, the state must preserve ordering; ordered structures generally cost O(log k) per update rather than constant time.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →How to solve a variable-width window problem
Example: longest substring without repeated characters
Maintain the most recent index for each character. When the right edge reaches a character whose previous occurrence lies inside the current window, move the left edge to one position after that occurrence. Then record the largest window length seen.
Rank #3
For instance, in abca, the second a repeats a character still inside the window. Move the left boundary past the earlier a; do not move it backward if the recorded last-seen index is already outside the current window. This keeps the window valid while the right edge continues forward.
Example: longest repeating character replacement
For the uppercase-letter version of this problem, track character frequencies in the window. A window is valid when its size is no greater than the most frequent character count plus the allowed number of replacements, k. If it becomes invalid, advance the left edge and update the state as required by the chosen implementation. The uppercase alphabet in this example permits a 26-entry array; arbitrary Unicode or an unbounded character set needs a representation suited to that input.
Rank #4
- Binding: paperback
- Language: english
- It ensures you get the best usage for a longer period
Record the answer at the right time
For a longest valid window, expand the right edge and shrink until the window is valid, then compare its length with the best answer. For a shortest valid window, record a valid candidate before shrinking it further to look for a shorter one. The ordering depends on the objective and validity condition; a template should not decide it for you.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsWhich state should you maintain?
- Running sum: Useful for sum constraints when values and the condition make the window’s behavior predictable.
- Frequency map or array: Useful for distinct-character counts, anagrams, and other frequency constraints. A fixed-size array can use constant space for a fixed alphabet; a map’s size can grow with the number of distinct values in the active window.
- Last-seen positions: Useful when a repeated item lets you jump the left boundary directly past its previous occurrence.
- Monotone deque: Useful for maintaining a fixed-window minimum or maximum without rescanning the whole window.
- Ordered structure: Useful for medians and other order-sensitive statistics, with extra update cost—typically O(log k) for median maintenance.
Choose the smallest state that lets you test the window’s condition and update it correctly when items enter or leave.
Best Value
Check whether the condition really supports a sliding window
The familiar variable-window rule for finding the longest subarray with sum at most S relies on non-negative values. Adding a value cannot lower the sum, and removing a value from the left cannot raise it. That predictable behavior makes it possible to move the left boundary whenever the sum exceeds the limit.
Negative values break that reasoning: extending a range can decrease its sum, while shrinking it can increase the sum. The usual greedy boundary movement may therefore skip valid answers. Use a different method, such as prefix sums with an appropriate lookup structure, when the exact problem and objective call for it. Calling a problem a “sliding window” problem is not enough to establish that the standard two-pointer rule is correct.
Understand the time and space costs
- Time: With forward-only pointers and constant-time state updates, the total pass is O(n). The left pointer may move many times in one iteration, but it advances at most n times over the whole run. ETH Zürich’s 2025 exercise handout gives a maximum of 2n pointer increments for its non-negative subarray-sum method: ETH Zürich exercise handout.
- State updates: If an update costs O(log n), the overall cost can be O(n log n) rather than O(n). The complexity follows from the update operation, not the technique’s name.
- Space: The amount depends on the maintained state. A fixed-alphabet array can be constant-sized; a frequency map or ordered structure uses space based on the active values or items.
Practice in a useful order
- Start with fixed-width sums, including maximum sum over
kconsecutive values. - Try longest substring without repeated characters, using last-seen positions.
- Practice a variable-width frequency constraint, then a fixed-window minimum or maximum using a deque.
- Test edge cases: empty and one-element inputs,
k = 1,kequal to the input length, repeated values, a constraint that never becomes valid, and negative values where applicable.
For another explanation of the window definition and the uppercase-letter replacement example, see the UCSD Competitive Programming Club’s Week 5 — Two Pointers lesson. The AlgoWiki sliding-window guide also discusses window state, variants, and complexity.
Free tools Windows power users keep installed
One-click scans. No signup required.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




