Pattern - Sliding Window
How to spot a sliding window problem, why it turns O(n*k) or O(n^2) into O(n), the fixed and variable shapes with a precise invariant, three problems traced step by step (max sum of size k, longest substring without repeats, minimum size subarray with sum at least a target), the amortized proof, the atMost trick for 'exactly k', and the cases where the pattern breaks.
Picture a picture frame sliding along a long strip of photos. The frame always shows a contiguous run. To move it you do two cheap things: let one new photo in on the right, and push old photos out on the left. You never rebuild what the frame shows from scratch; you only adjust for what entered and what left. In a fixed window the frame has a set width and both edges move together. In a variable window the right edge always advances, and the left edge moves only to repair a rule the frame just broke. The left edge never moves backward, and that single fact is why the whole walk costs O(n).
Builds on
- Big-O notation — the whole point of the pattern is a complexity improvement, and the amortized argument needs you to count operations.
- Arrays in memory — a window is a range of indices into an array or string, and index access must be O(1).
- Hash maps — most variable windows keep a map or set of what is currently inside, so you need O(1) average lookup and update.
Spot it: when a problem is a sliding window
Many interview problems ask you to look at a stretch of consecutive elements: the best five days of sales, the longest piece of text with no repeated letter, the shortest run of numbers adding up to at least a target. The tempting first idea is to check every possible stretch. That works but is slow, because neighbouring stretches overlap almost completely and you redo the same work again and again. A sliding window is the technique for not redoing it: you keep one stretch, called the window, and move it along the data, adjusting its summary as elements enter on the right and leave on the left.
You can recognize the pattern from the wording. There are three signals, and you want all three. First, the answer is about a contiguous range: the words subarray, substring, consecutive, in a row, or a window of size k. Second, the goal is to optimize or count over such ranges: longest, shortest, maximum sum, at most k distinct, count of ranges. Third, the rule that makes a range good can be maintained as you add and remove one element at a time, such as a running sum, a count of each letter, or a count of distinct letters.
| Phrase in the problem | Shape | Typical state | Example |
|---|---|---|---|
| maximum or minimum sum of k consecutive | fixed window | running sum | best five-day revenue |
| longest substring with no repeats | variable window | last-seen map or set | Longest Substring Without Repeating Characters |
| shortest subarray with sum at least a target | variable window | running sum | minimum size subarray sum |
| longest with at most k distinct | variable window | counter map | two fruit baskets |
| smallest range containing all required letters | variable window | counter map plus a satisfied count | Minimum window Substring |
| longest after at most k replacements | variable window | counter map plus the max count | Longest Repeating Character Replacement |
A quick test before you commit: say the problem in one sentence starting with 'among all consecutive stretches'. If that sentence is natural, and you can describe how the answer for the stretch ending at position r follows from the one ending at r - 1 by adding one element and maybe removing some from the front, you have a window problem.
Check yourself
Which problem is a sliding window problem?
The numbers: brute force versus the window
Take the simplest fixed-window problem: given an array of n numbers and a size k, find the largest sum of k consecutive numbers. The brute force tries every starting index, and for each one adds up k numbers. There are n - k + 1 starting positions, so the number of additions is (n - k + 1) * k. The window does better because two neighbouring windows share k - 1 elements. To go from the window starting at i to the one starting at i + 1 you add one number and subtract one, instead of summing k numbers again.
| n | k | Brute force (n-k+1)*k | Window k + 2(n-k) | Ratio |
|---|---|---|---|---|
| 6 | 3 | 12 | 9 | 1.3x |
| 10 | 4 | 28 | 16 | 1.75x |
| 100,000 | 50,000 | 2,500,050,000 | 150,000 | 16,667x |
Notice that the cost of brute force depends on k while the window does not. With k = n / 2 the brute force is about n^2 / 4 additions, which for n = 100,000 is 2.5 billion: far too slow for a typical time limit of around a second, since a computer manages very roughly a hundred million to a billion simple operations per second. The window needs about 1.5 times n operations.
The same story holds for variable windows. A longest-substring brute force checks every start and end pair, which is n * (n + 1) / 2 ranges (5,000,050,000 for n = 100,000), and checking one range for duplicates costs up to its length. That makes it O(n^2) at best and O(n^3) if you re-check naively. The window keeps a set of what is inside and visits each position a constant number of times.
Check yourself
n = 10 and k = 4. How many additions does the brute force fixed-window sum perform?
Shape one: the fixed-size window
In a fixed window the length k is given. The right edge is the loop variable and the left edge is always right - k + 1, so you do not even need a separate left variable: the element that leaves when right arrives is arr[right - k]. The loop has two phases. For the first k elements you only add. From index k on, you add the new element and subtract the one that just left, then compare the current sum to the best.
function maxSumK(arr, k) { let sum = 0; for (let i = 0; i < k; i++) sum += arr[i]; // first window let best = sum; for (let right = k; right < arr.length; right++) { sum += arr[right] - arr[right - k]; // enter right, leave right - k if (sum > best) best = sum; } return best;}console.log(maxSumK([2, 1, 5, 1, 3, 2], 3)); // 9console.log(maxSumK([1, 8, 2, 9, 4], 3)); // 19Walk through [2, 1, 5, 1, 3, 2] with k = 3. The first window [2, 1, 5] has sum 8. Slide: add 1, remove 2, sum 7 (window [1, 5, 1]). Slide: add 3, remove 1, sum 9 (window [5, 1, 3]). Slide: add 2, remove 5, sum 6 (window [1, 3, 2]). The best is 9. There are n - k + 1 = 4 windows, and the Trace tab shows each of them with its left and right pointers.
The same skeleton works for any aggregate that can be undone: sums, counts, counts of vowels, number of ones in a binary array. If the aggregate cannot be undone (a plain maximum, for example) you need a helper structure, which is the topic of the data-structure section below.
Check yourself
In maxSumK, which element leaves the window when right = 4 and k = 3?
Shape two: the variable-size window and its invariant
In a variable window nobody tells you the length; finding the best length is the question. You still use two indices. The right edge advances by one on every iteration of an outer loop and the new element is added to the state. If that addition breaks the rule, the left edge advances (removing elements from the state) until the rule holds again. The answer is recorded from the window at the moment the rule is satisfied.
function slidingWindow(arr) { let left = 0; let best = 0; // or Infinity for a minimum // state = an empty sum, set, or map for (let right = 0; right < arr.length; right++) { // 1. add arr[right] to state while (/* state is invalid */ false) { // 2. remove arr[left] from state left++; } // 3. window [left, right] is valid here: update best best = Math.max(best, right - left + 1); } return best;}There are two flavours of recording. When you are looking for the longest valid window, the rule is that the window is valid after shrinking, so you record after the while loop. When you are looking for the shortest window that satisfies a goal (a sum at least a target), the window becomes valid by growing, so you record inside the while loop and keep shrinking for as long as it stays valid. Getting this placement wrong is one of the most common bugs, covered below.
| Goal | While loop condition | Where to record | Why |
|---|---|---|---|
| longest valid | window is invalid | after the loop | the loop restored validity; the window is the longest ending at right |
| shortest satisfying | window still satisfies the goal | inside the loop, before removing arr[left] | each pass is a smaller window that still satisfies the goal |
Check yourself
For a longest-valid-window problem, where do you update the answer?
Worked problem: longest substring without repeating characters
Given a string, return the length of the longest substring with no repeated character. The rule is 'every character in the window is distinct'. It is monotone: removing characters from a valid window keeps it valid, and adding one can break it. That is what makes the shrink strategy correct. See the full algorithm lesson at Longest Substring Without Repeating Characters.
There are two standard implementations. The set version shrinks one step at a time: while the new character is already in the set, delete s[left] and move left. The last-seen map version stores the latest index of each character, and when it meets a duplicate it jumps left directly to one past the previous occurrence. Both are O(n).
function longestUnique(s) { const last = new Map(); // char -> most recent index let left = 0, best = 0; for (let right = 0; right < s.length; right++) { const c = s[right]; if (last.has(c) && last.get(c) >= left) { left = last.get(c) + 1; // jump past the old copy } last.set(c, right); best = Math.max(best, right - left + 1); } return best;}console.log(longestUnique('tmmzuxt')); // 5 (mzuxt)console.log(longestUnique('abcabcbb')); // 3 (abc)console.log(longestUnique('')); // 0console.log(longestUnique('bbbb')); // 1The condition last.get(c) >= left is the stale entry check. The map is never cleaned, so it may remember a character at an index that is already left of the window. In 'tmmzuxt', when the final t arrives at index 6, the map says t was last at index 0, but left is already 2. That t is no longer inside the window, so there is no conflict and left must stay put. Without the check, left would jump backward to 1 and the window would wrongly include the second m, reporting 6 instead of 5.
function longestUniqueSet(s) { const seen = new Set(); let left = 0, best = 0; for (let right = 0; right < s.length; right++) { while (seen.has(s[right])) seen.delete(s[left++]); seen.add(s[right]); best = Math.max(best, right - left + 1); } return best;}console.log(longestUniqueSet('abcabcbb')); // 3Check yourself
In the last-seen map version, what does the check last.get(c) >= left protect against?
Worked problem: minimum size subarray with sum at least a target
Given positive integers and a target, return the length of the shortest contiguous subarray whose sum is at least the target, or 0 if none exists. Here the window becomes valid by growing, so we record inside the while loop and keep shrinking for as long as the sum is still at least the target.
function minSubArrayLen(target, nums) { let left = 0, sum = 0, best = Infinity; for (let right = 0; right < nums.length; right++) { sum += nums[right]; while (sum >= target) { // while the goal is still met best = Math.min(best, right - left + 1); sum -= nums[left++]; } } return best === Infinity ? 0 : best;}console.log(minSubArrayLen(7, [2, 3, 1, 2, 4, 3])); // 2 ([4, 3])console.log(minSubArrayLen(100, [1, 2])); // 0console.log(minSubArrayLen(4, [1, 4, 4])); // 1Why is this correct? Because all numbers are positive, a longer window always has a larger sum. If [left, right] meets the target, then any window that starts before left and ends at right also does, but it is longer and so cannot be the shortest; therefore we only care about the largest left that still works, and the shrink loop finds exactly that. If [left, right] does not meet the target, moving left forward only lowers the sum, so we must move right instead.
The code uses Infinity as the starting minimum, then converts to 0 at the end if no window was ever found. Using 0 as the initial best would make Math.min return 0 forever.
Check yourself
In minSubArrayLen, why is the answer recorded inside the while loop?
Why it is O(n): the left pointer never moves backward
A while loop inside a for loop looks like O(n^2). It is not, and being able to explain why is a standard interview question. The key is that you should not multiply the cost of one iteration by the number of iterations; you should count the total work done by all iterations together.
Right moves exactly n times
the outer for loop advances right once per iteration and never goes back.
Left only moves forward
every execution of the while body does left++ and nothing in the algorithm ever decreases left.
Left never passes right
the window may be empty, so left is at most right + 1, which is at most n.
So left moves at most n times in total
the while body, summed over all outer iterations, runs at most n times.
Count it on a real run. For 'abcabcbb' with the set version, right moves 8 times and left moves 5 times (it ends at index 5), for 13 moves in total, and 13 is at most 2 * 8 = 16. For the minimum-size run [2, 3, 1, 2, 4, 3] with target 7, right moves 6 times and left moves 5 times, 11 moves in total, at most 12. A single outer iteration can run the while loop several times (the run for [2, 3, 1, 2, 4, 3] removes two elements when right = 4), but then other iterations remove none.
| Run | n | Right moves | Left moves | Total | Bound 2n |
|---|---|---|---|---|---|
| longest unique, 'abcabcbb', set version | 8 | 8 | 5 | 13 | 16 |
| min size, target 7, [2,3,1,2,4,3] | 6 | 6 | 5 | 11 | 12 |
Check yourself
A variable window has a while loop inside the for loop. Why is the total time still O(n)?
Counting windows, and 'exactly k' as atMost(k) minus atMost(k - 1)
Sometimes the question is to count windows, not to find the longest one. The key observation: after the shrink loop, every window that ends at right and starts anywhere between left and right is valid (if the rule is monotone), because shrinking a valid window keeps it valid. That is right - left + 1 new valid windows for this right edge. Summing that over every right edge counts all valid windows in O(n).
A condition of 'exactly k' (exactly k distinct letters, a sum of exactly goal) is not monotone: growing a window can pass through exactly k and out the other side, and shrinking can pass through it too. The fix is to count a monotone condition twice. Windows with at most k are monotone, and windows with exactly k are those with at most k minus those with at most k - 1.
function atMost(nums, goal) { if (goal < 0) return 0; let left = 0, sum = 0, count = 0; for (let right = 0; right < nums.length; right++) { sum += nums[right]; while (sum > goal) sum -= nums[left++]; count += right - left + 1; // windows ending at right } return count;}function exactly(nums, goal) { return atMost(nums, goal) - atMost(nums, goal - 1);}const b = [1, 0, 1, 0, 1];console.log(atMost(b, 2)); // 14console.log(atMost(b, 1)); // 10console.log(exactly(b, 2)); // 4Check by hand. The array [1, 0, 1, 0, 1] has 5 * 6 / 2 = 15 subarrays. Exactly one has sum 3 (the whole array), so 14 have sum at most 2. Subarrays with sum at most 1: 15 minus those with sum 2 or 3. There are 4 with sum 2 and 1 with sum 3, leaving 10. Then 14 - 10 = 4. The four are [1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1] (the last two positions).
Check yourself
You can count windows with at most 3 distinct letters. How do you count windows with exactly 3?
When the window does NOT apply
The shrink step is only justified when the rule is monotone: growing the window can only move it toward invalid and shrinking can only move it toward valid (or the reverse for the shortest-goal flavour). A sum of positive numbers is monotone. A sum with negative numbers is not, because adding an element can lower the sum and removing one can raise it.
Here is a counterexample. Find the shortest subarray with sum at least 167 in [84, -37, 32, 40, 95]. The real answer is 3: the last three numbers 32 + 40 + 95 = 167. Run the window code from the previous section: after right = 4 the sum is 84 - 37 + 32 + 40 + 95 = 214, which is at least 167, so it records length 5 and removes 84, leaving 130, which is below 167, so it stops. It never sees that dropping the -37 prefix as well would have helped, because left only moves while the sum is still at least the target. The code returns 5; the correct answer is 3.
function minLenWindow(target, a) { let left = 0, sum = 0, best = Infinity; for (let right = 0; right < a.length; right++) { sum += a[right]; while (sum >= target) { best = Math.min(best, right - left + 1); sum -= a[left++]; } } return best;}function minLenBrute(target, a) { let best = Infinity; for (let i = 0; i < a.length; i++) { let sum = 0; for (let j = i; j < a.length; j++) { sum += a[j]; if (sum >= target) { best = Math.min(best, j - i + 1); break; } } } return best;}console.log(minLenWindow(167, [84, -37, 32, 40, 95])); // 5 (wrong)console.log(minLenBrute(167, [84, -37, 32, 40, 95])); // 3 (correct)The tools for sums with negatives are prefix sums (each window sum is a difference of two prefix values) combined with a monotonic deque or, for exact sums, a hash map from prefix value to index. That is how Max Subarray is solved without any window: Kadane's idea keeps one running best and does not shrink.
| Situation | Why a window fails | Use instead |
|---|---|---|
| sum constraint with negative numbers | growing can lower the sum; shrinking can raise it | prefix sums plus a deque or hash map |
| choose elements anywhere (pairs, subsets) | the chosen elements are not a range | hash map (Two Sum), sorting plus two pointers, backtracking |
| window both ends move inward from the sides | the two pointers start at opposite ends | opposite-end two pointers (Container With Most Water, Trapping Rain Water) |
| constraint not monotone (exactly k) | validity flips as you grow | atMost(k) - atMost(k - 1) |
Check yourself
Why does the sliding window fail for the shortest subarray with sum at least a target when negatives are allowed?
What lives inside the window: choosing the data structure
A window is only fast if updating its summary costs O(1) per element. The choice of structure depends on what the rule asks.
| Rule | State | Add / remove cost | Space |
|---|---|---|---|
| sum or count of ones | one number | O(1) / O(1) | O(1) |
| all characters distinct | set, or last-seen map | O(1) average / O(1) average | O(min(n, alphabet)) |
| at most k distinct | counter map (delete entries at zero) | O(1) average / O(1) average | O(k + 1) |
| cover all required letters | counter map plus a counter of satisfied letters | O(1) average / O(1) average | O(alphabet) |
| maximum or minimum of every window | monotonic deque of indices | O(1) amortized / O(1) | O(k) |
The counter map version of 'longest substring with at most k distinct characters' increments a count when a character enters, and decrements it when one leaves. The number of distinct characters is the map size, so you must delete a key when its count reaches zero; leaving zero-count entries makes the size wrong. On 'eceba' with k = 2 the answer is 3 ('ece').
function longestKDistinct(s, k) { const count = new Map(); let left = 0, best = 0; for (let right = 0; right < s.length; right++) { count.set(s[right], (count.get(s[right]) || 0) + 1); while (count.size > k) { const c = s[left++]; count.set(c, count.get(c) - 1); if (count.get(c) === 0) count.delete(c); // keep size honest } best = Math.max(best, right - left + 1); } return best;}console.log(longestKDistinct('eceba', 2)); // 3A maximum is the awkward one: you can add a number to a running maximum, but you cannot subtract one. Recomputing the maximum of k elements on every slide costs O(n*k). The standard answer is a monotonic deque that stores indices whose values are in decreasing order. When arr[right] arrives, pop smaller values from the back (they can never be the maximum again), push right, drop the front if its index has left the window, and read the front as the maximum.
function windowMax(a, k) { const dq = []; // indices, values decreasing const out = []; for (let i = 0; i < a.length; i++) { while (dq.length && a[dq[dq.length - 1]] <= a[i]) dq.pop(); dq.push(i); if (dq[0] <= i - k) dq.shift(); // front left the window if (i >= k - 1) out.push(a[dq[0]]); } return out;}console.log(windowMax([1, 3, -1, -3, 5, 3, 6, 7], 3));Each index is pushed once and popped at most once, so the deque is O(n) in total, again by the amortized argument. Note that array.shift is O(n) in some engines for large arrays; in production code, track a head index into the array instead of shifting. For interviews, shift is accepted if you mention it.
Check yourself
In the counter map version for at most k distinct characters, why delete a key when its count hits zero?
Common wrong turns
| Failure | Impact | Defense |
|---|---|---|
| shrink with if instead of while | the window stays invalid after one removal; wrong answers on inputs needing two removals | always use while for shrinking, and prove the invariant after it |
| length as right - left | every length is one too small | length is right - left + 1; check with a window of one element |
| recording at the wrong time | record before shrinking when you wanted validity, or after the loop when you wanted the shortest | longest: after the loop; shortest: inside the loop |
| stale map entry moves left backward | window grows to include a duplicate | left = max(left, last[c] + 1) or check last[c] >= left |
| recomputing state each iteration | silently O(n*k) | update the state incrementally on enter and exit |
| initial best 0 for a minimum | Math.min never gets updated; the answer is 0 | start at Infinity and convert at the end |
| zero-count key left in a counter map | distinct count too high | delete the key when the count reaches zero |
The first is worth showing. In the minimum-size run on [2, 3, 1, 2, 4, 3] with target 7, the step at right = 4 needs two removals (sum 10 to 7 to 6). With if, left moves once and the length-3 window is never recorded. With while, left advances exactly as far as needed.
Check yourself
A window has length r - l + 1. For l = 3 and r = 3, what is the length?
Timed interview script
01Restate (1 min)
Repeat the problem and confirm that the range must be contiguous, what the elements are (positive only?), and what to return when no window exists.
02Brute force (2 min)
Describe trying every start and end, and state its cost: n^2 ranges, or (n - k + 1) * k for a fixed window. Say that neighbouring ranges overlap heavily.
03Window idea (3 min)
Introduce left and right. Say what the state is and how to add and remove one element in O(1). Say whether the window is fixed or variable.
04Invariant (2 min)
State: after the shrink loop the window is valid, and left is as small as possible. Explain why the rule is monotone for this input.
05Code (8 min)
Write the template. Put the record step where it belongs (after the loop for longest, inside for shortest). Use right - left + 1.
06Verify and cost (4 min)
Dry-run a small example, test empty and all-equal inputs, and state O(n) time because each element enters and leaves once, with O(k) or O(alphabet) space.
Recap
Recognize it: a contiguous subarray or substring, plus longest, shortest, at most k, or a running aggregate such as a sum or a count.
Brute force re-examines overlapping ranges: about (n - k + 1) * k additions for a fixed window, or about n^2 / 2 ranges for a variable one. The window reuses the overlap and does O(1) work per move.
fixed window: add the entering element, subtract the leaving one, record. variable window: add arr[right], shrink with a while loop until valid, then record.
The invariant for a variable window: after the shrink loop the window [left, right] is valid, and left is the smallest index for which that holds.
amortized O(n): right moves n times and left never moves backward and never passes right, so it moves at most n times. Total pointer moves are at most 2n.
Exactly k = atMost(k) - atMost(k - 1). Each call is a normal variable window that counts r - l + 1 new windows ending at r.
A sum constraint needs non-negative numbers. With negatives, growing can lower the sum and the shrink rule is no longer monotone, so use prefix sums with a deque or a map.
window state must update in O(1): a running sum, a counter map, a last-seen map, or a deque for window max.
Wrong turns: if instead of while, length without the + 1, recording the answer at the wrong moment, and a last-seen entry that points left of the window.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
data structure
A way of organizing data in memory (array, tree, map) that determines which operations are fast.
sliding window
Keeping a range of the array and sliding its edges, instead of recomputing from scratch.
two pointers
Moving two indices through an array to meet a condition in one pass instead of nested loops.
backtracking
Trying every choice, and undoing the last one when it dead-ends - systematic trial and error.
amortized
Cost averaged over the whole run instead of per step. One step may be expensive, but the total is small.
A yearly gym fee: one big payment, but cheap per visit.
algorithm
A precise, step-by-step procedure that solves a problem.
invariant
A statement that is true at the start of every loop iteration. For a variable window: after the shrink loop, the window satisfies the rule.
A promise the loop keeps every time it comes back to the top.
hash map
A key-value store using a hash function for average O(1) lookups, inserts, and deletes.
ASCIIAmerican Standard Code for Information Interchange
A 7-bit encoding for 128 basic English characters - the common subset every encoding preserves.
dequedouble-ended queue
A queue you can add to and remove from at both ends in O(1). It holds window-max candidates in decreasing order.
window
The contiguous range of positions from left to right (both included) that you are currently examining. Its length is right - left + 1.
The picture frame.
contiguous
Occupying neighbouring positions with no gaps. A subarray or substring is contiguous; a subsequence is not.
A row of seats where everyone sits side by side.
fixed window
A window whose length is a given constant k. Both edges advance together.
variable window
A window whose length changes: the right edge always advances and the left edge advances only to restore a rule.
monotone
Moving in only one direction. A rule is monotone for a window if growing the window can only push it toward invalid and shrinking can only push it toward valid.
last-seen map
A map from a value to the most recent index where it appeared, which lets the left edge jump straight past a duplicate.
counter map
A map from a value to how many times it currently appears in the window, incremented on entry and decremented on exit.
atMost trick
Counting windows with exactly k of something as the count with at most k minus the count with at most k - 1.
off-by-one
An error where a boundary is wrong by exactly one, such as using right - left as the length instead of right - left + 1.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixUse while for shrinking, so left advances exactly as far as needed to restore the rule.
FixUse right - left + 1, because both edges are inclusive.
FixGuard with last[c] >= left and update the state incrementally, so left only moves forward and each step is O(1).
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
I look for three things: the answer concerns a contiguous subarray or substring, the goal is to optimize or count (longest, shortest, at most k, max sum), and the rule can be updated by adding one element on the right and removing one on the left. If the elements can be chosen from anywhere, it is not a window problem.
recognition: seconds
Real worldRolling averages in monitoring dashboards are fixed windows over the most recent samples.
DeeperWhat if the array can contain negative numbers?