TheScalableDev
PatternsIntermediate50 minO(n) time · O(1) to O(k) spaceFree

Pattern - Sliding Window

Status

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.

BestO(n)AverageO(n)WorstO(n)SpaceO(k)

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.
01recognition costs nothing; the payoff is O(n)

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 problemShapeTypical stateExample
maximum or minimum sum of k consecutivefixed windowrunning sumbest five-day revenue
longest substring with no repeatsvariable windowlast-seen map or setLongest Substring Without Repeating Characters
shortest subarray with sum at least a targetvariable windowrunning summinimum size subarray sum
longest with at most k distinctvariable windowcounter maptwo fruit baskets
smallest range containing all required lettersvariable windowcounter map plus a satisfied countMinimum window Substring
longest after at most k replacementsvariable windowcounter map plus the max countLongest Repeating Character Replacement
Signal words and the window shape they suggest

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?

02from 2,500,050,000 additions to 150,000

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.

brute = (n - k + 1) * k window = k + 2 * (n - k)
Additions or subtractions: the brute force re-adds every element; the window pays k once, then two operations per slide.
nkBrute force (n-k+1)*kWindow k + 2(n-k)Ratio
631291.3x
10428161.75x
100,00050,0002,500,050,000150,00016,667x
Exact counts. Checked by counting operations in node.

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.

ranges(n) = n * (n + 1) / 2 n = 100,000 -> 5,000,050,000
Number of distinct start-and-end ranges in a string of length n.

Check yourself

n = 10 and k = 4. How many additions does the brute force fixed-window sum perform?

03O(n) time · O(1) space

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.

Maximum sum of k consecutive elements. Output: 9 and 19.
1function maxSumK(arr, k) {
2 let sum = 0;
3 for (let i = 0; i < k; i++) sum += arr[i]; // first window
4 let best = sum;
5 for (let right = k; right < arr.length; right++) {
6 sum += arr[right] - arr[right - k]; // enter right, leave right - k
7 if (sum > best) best = sum;
8 }
9 return best;
10}
11console.log(maxSumK([2, 1, 5, 1, 3, 2], 3)); // 9
12console.log(maxSumK([1, 8, 2, 9, 4], 3)); // 19

Walk 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?

04O(n) time · state-dependent space

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.

The universal template. Replace add, remove and invalid for each problem.
1function slidingWindow(arr) {
2 let left = 0;
3 let best = 0; // or Infinity for a minimum
4 // state = an empty sum, set, or map
5 for (let right = 0; right < arr.length; right++) {
6 // 1. add arr[right] to state
7 while (/* state is invalid */ false) {
8 // 2. remove arr[left] from state
9 left++;
10 }
11 // 3. window [left, right] is valid here: update best
12 best = Math.max(best, right - left + 1);
13 }
14 return best;
15}

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.

GoalWhile loop conditionWhere to recordWhy
longest validwindow is invalidafter the loopthe loop restored validity; the window is the longest ending at right
shortest satisfyingwindow still satisfies the goalinside the loop, before removing arr[left]each pass is a smaller window that still satisfies the goal
Two recording styles

Check yourself

For a longest-valid-window problem, where do you update the answer?

05O(n) time · O(min(n, alphabet)) space

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).

Last-seen map version. Output: 5, 3, 0, 1.
1function longestUnique(s) {
2 const last = new Map(); // char -> most recent index
3 let left = 0, best = 0;
4 for (let right = 0; right < s.length; right++) {
5 const c = s[right];
6 if (last.has(c) && last.get(c) >= left) {
7 left = last.get(c) + 1; // jump past the old copy
8 }
9 last.set(c, right);
10 best = Math.max(best, right - left + 1);
11 }
12 return best;
13}
14console.log(longestUnique('tmmzuxt')); // 5 (mzuxt)
15console.log(longestUnique('abcabcbb')); // 3 (abc)
16console.log(longestUnique('')); // 0
17console.log(longestUnique('bbbb')); // 1

The 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.

The set version: shrink one step at a time with while. Same answers.
1function longestUniqueSet(s) {
2 const seen = new Set();
3 let left = 0, best = 0;
4 for (let right = 0; right < s.length; right++) {
5 while (seen.has(s[right])) seen.delete(s[left++]);
6 seen.add(s[right]);
7 best = Math.max(best, right - left + 1);
8 }
9 return best;
10}
11console.log(longestUniqueSet('abcabcbb')); // 3

Check yourself

In the last-seen map version, what does the check last.get(c) >= left protect against?

06O(n) time · O(1) space

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.

Output: 2, 0, 1.
1function minSubArrayLen(target, nums) {
2 let left = 0, sum = 0, best = Infinity;
3 for (let right = 0; right < nums.length; right++) {
4 sum += nums[right];
5 while (sum >= target) { // while the goal is still met
6 best = Math.min(best, right - left + 1);
7 sum -= nums[left++];
8 }
9 }
10 return best === Infinity ? 0 : best;
11}
12console.log(minSubArrayLen(7, [2, 3, 1, 2, 4, 3])); // 2 ([4, 3])
13console.log(minSubArrayLen(100, [1, 2])); // 0
14console.log(minSubArrayLen(4, [1, 4, 4])); // 1

Why 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?

07at most 2n pointer moves

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.

total pointer moves <= n + n = 2n -> O(n)
Right contributes n moves, left at most n moves. Each element is added to the state once and removed at most once.

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.

RunnRight movesLeft movesTotalBound 2n
longest unique, 'abcabcbb', set version8851316
min size, target 7, [2,3,1,2,4,3]6651112
Counted runs (verified in node)

Check yourself

A variable window has a while loop inside the for loop. Why is the total time still O(n)?

08two O(n) passes

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.

Count subarrays of a 0/1 array with sum exactly goal. Output: 14, 10, 4.
1function atMost(nums, goal) {
2 if (goal < 0) return 0;
3 let left = 0, sum = 0, count = 0;
4 for (let right = 0; right < nums.length; right++) {
5 sum += nums[right];
6 while (sum > goal) sum -= nums[left++];
7 count += right - left + 1; // windows ending at right
8 }
9 return count;
10}
11function exactly(nums, goal) {
12 return atMost(nums, goal) - atMost(nums, goal - 1);
13}
14const b = [1, 0, 1, 0, 1];
15console.log(atMost(b, 2)); // 14
16console.log(atMost(b, 1)); // 10
17console.log(exactly(b, 2)); // 4

Check 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?

09wrong answers, not just slow ones

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.

The window code run on negative input. Output: 5 (wrong), then the brute force gives 3.
1function minLenWindow(target, a) {
2 let left = 0, sum = 0, best = Infinity;
3 for (let right = 0; right < a.length; right++) {
4 sum += a[right];
5 while (sum >= target) { best = Math.min(best, right - left + 1); sum -= a[left++]; }
6 }
7 return best;
8}
9function minLenBrute(target, a) {
10 let best = Infinity;
11 for (let i = 0; i < a.length; i++) {
12 let sum = 0;
13 for (let j = i; j < a.length; j++) {
14 sum += a[j];
15 if (sum >= target) { best = Math.min(best, j - i + 1); break; }
16 }
17 }
18 return best;
19}
20console.log(minLenWindow(167, [84, -37, 32, 40, 95])); // 5 (wrong)
21console.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.

SituationWhy a window failsUse instead
sum constraint with negative numbersgrowing can lower the sum; shrinking can raise itprefix sums plus a deque or hash map
choose elements anywhere (pairs, subsets)the chosen elements are not a rangehash map (Two Sum), sorting plus two pointers, backtracking
window both ends move inward from the sidesthe two pointers start at opposite endsopposite-end two pointers (Container With Most Water, Trapping Rain Water)
constraint not monotone (exactly k)validity flips as you growatMost(k) - atMost(k - 1)
When to reach for something else

Check yourself

Why does the sliding window fail for the shortest subarray with sum at least a target when negatives are allowed?

10O(1) per update keeps the whole run O(n)

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.

RuleStateAdd / remove costSpace
sum or count of onesone numberO(1) / O(1)O(1)
all characters distinctset, or last-seen mapO(1) average / O(1) averageO(min(n, alphabet))
at most k distinctcounter map (delete entries at zero)O(1) average / O(1) averageO(k + 1)
cover all required letterscounter map plus a counter of satisfied lettersO(1) average / O(1) averageO(alphabet)
maximum or minimum of every windowmonotonic deque of indicesO(1) amortized / O(1)O(k)
Window state by problem type

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').

At most k distinct (counter map). Output: 3.
1function longestKDistinct(s, k) {
2 const count = new Map();
3 let left = 0, best = 0;
4 for (let right = 0; right < s.length; right++) {
5 count.set(s[right], (count.get(s[right]) || 0) + 1);
6 while (count.size > k) {
7 const c = s[left++];
8 count.set(c, count.get(c) - 1);
9 if (count.get(c) === 0) count.delete(c); // keep size honest
10 }
11 best = Math.max(best, right - left + 1);
12 }
13 return best;
14}
15console.log(longestKDistinct('eceba', 2)); // 3

A 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.

Maximum of every window of size k. Output: [3, 3, 5, 5, 6, 7].
1function windowMax(a, k) {
2 const dq = []; // indices, values decreasing
3 const out = [];
4 for (let i = 0; i < a.length; i++) {
5 while (dq.length && a[dq[dq.length - 1]] <= a[i]) dq.pop();
6 dq.push(i);
7 if (dq[0] <= i - k) dq.shift(); // front left the window
8 if (i >= k - 1) out.push(a[dq[0]]);
9 }
10 return out;
11}
12console.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?

11each costs a wrong answer on a hidden test

Common wrong turns

FailureImpactDefense
shrink with if instead of whilethe window stays invalid after one removal; wrong answers on inputs needing two removalsalways use while for shrinking, and prove the invariant after it
length as right - leftevery length is one too smalllength is right - left + 1; check with a window of one element
recording at the wrong timerecord before shrinking when you wanted validity, or after the loop when you wanted the shortestlongest: after the loop; shortest: inside the loop
stale map entry moves left backwardwindow grows to include a duplicateleft = max(left, last[c] + 1) or check last[c] >= left
recomputing state each iterationsilently O(n*k)update the state incrementally on enter and exit
initial best 0 for a minimumMath.min never gets updated; the answer is 0start at Infinity and convert at the end
zero-count key left in a counter mapdistinct count too highdelete the key when the count reaches zero
Failure modes, impact and defense

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?

12about 20 minutes

Timed interview script

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  1. FixUse while for shrinking, so left advances exactly as far as needed to restore the rule.

  2. FixUse right - left + 1, because both edges are inclusive.

  3. 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?