Skip to content

Sliding window: contiguous runs in a single pass

How to answer questions about contiguous subarrays and substrings in O(n): grow on the right, shrink on the left, never start over.

8 min readTime: O(n)Memory: O(1)AlgorithmsSliding window

Whenever a problem asks about a contiguous run — the longest stretch, the shortest slice, the best block of k in a row — the naive answer checks every start and every end and pays O(n²). A sliding window keeps one run alive and adjusts its two edges: the right edge always moves forward, the left edge only catches up when the run breaks the rule. Each element gets in once and out once, so the whole thing is linear.

The intuition

The picture to keep in your head.

Picture a strip of paper with a frame you can stretch. You slide the right side of the frame forward one cell at a time, and you keep a running summary of what's inside: a sum, a count per character, a set. As long as the inside obeys the rule, you note how good it is. The moment it doesn't, you pull the left side of the frame forward until it does again.

The trick that makes it fast is that you never move the left side backwards. A run that broke the rule at some left edge will keep breaking it if you extend it further right — so there's nothing to gain by revisiting old starts. That one-way movement is why two nested loops still add up to about 2n steps, not n².

The question to ask yourself before writing code: what does the window need to remember so that adding one element and removing one element are both cheap? If the answer is a number or a map you can update in O(1), the window works.

Step by step

Small, safe steps, with the tests passing after each.

  1. Step 1: Name the rule the window must satisfy

    Write it as a sentence: «total errors at most the budget», «no character twice», «exactly k elements». If you can't phrase it about the current run alone, it's probably not a window problem.

  2. Step 2: Pick the summary you'll keep updated

    A running sum, a map of counts, a set of what's inside. It must support «add the element entering on the right» and «remove the element leaving on the left» in constant time.

  3. Step 3: Grow on the right, one element per iteration

    The outer loop moves right across the input and adds that element to the summary. This loop runs exactly n times.

  4. Step 4: Shrink on the left while the rule is broken

    An inner while, not an if: one new element may need several removals before the window is valid again. Remove left from the summary, then advance it.

  5. Step 5: Record the answer at the right moment

    For «longest valid run», record after shrinking, when the window is valid. For «shortest run that reaches a target», record inside the shrinking loop, while it's still valid.

  6. Step 6: Check the edges out loud

    Empty input, a single element that breaks the rule on its own, everything valid from start to end. Say what your code returns for each before the interviewer asks.

What it costs

Time and memory, and why.

Time
O(n)
Memory
O(1)

Both edges only move forward and each stops at n, so the inner loop's work across the whole run is at most n removals: about 2n steps in total, even though the code has a loop inside a loop. Memory is whatever the summary needs: O(1) for a sum, O(k) for a map of counts where k is the alphabet or the number of distinct values allowed inside.

A traced example

A small input, followed step by step.

A server logs how many errors it had each minute: [0, 2, 1, 0, 3, 0, 1, 1]. What is the longest run of consecutive minutes with at most 3 errors in total?

  1. 1right=0 · window [0] · sum 0Valid. Best so far: 1 minute.
  2. 2right=1 · window [0, 2] · sum 2Valid. Best: 2.
  3. 3right=2 · window [0, 2, 1] · sum 3Exactly on budget still counts. Best: 3.
  4. 4right=3 · window [0, 2, 1, 0] · sum 3A quiet minute stretches the run for free. Best: 4.
  5. 5right=4 · add 3 → sum 6Over budget. Drop 0 (sum 6), drop 2 (sum 4), drop 1 (sum 3): window is now [0, 3].
  6. 6right=5 · window [0, 3, 0] · sum 3Valid, length 3. Best stays 4.
  7. 7right=6 · add 1 → sum 4Over again. Drop 0 (sum 4), drop 3 (sum 1): window [0, 1].
  8. 8right=7 · window [0, 1, 1] · sum 2Valid, length 3. The input is over.

Result: 4 — minutes 0 to 3. Eight elements, eight additions and five removals: no run was ever recomputed from scratch.

The code

The same solution in TypeScript, Python and PHP.

function longestCalmStretch(errors: number[], budget: number): number {
  let left = 0;
  let sum = 0; // errors inside the window [left, right]
  let best = 0;
  for (let right = 0; right < errors.length; right++) {
    sum += errors[right];
    // Too many errors inside: shrink from the left until it fits again.
    while (sum > budget) {
      sum -= errors[left];
      left++;
    }
    best = Math.max(best, right - left + 1);
  }
  return best;
}

longestCalmStretch([0, 2, 1, 0, 3, 0, 1, 1], 3); // 4

Variants

Shapes the same idea takes.

  • Fixed size k

    When: «The best block of exactly k in a row»: a k-day moving total, the busiest hour.

    No inner loop at all. Add the element entering, subtract the one that falls out at right - k, and start recording once the window has k elements.

  • Longest valid run

    When: «The longest stretch such that…» and the rule only gets harder to satisfy as the run grows.

    The pattern in the code above: shrink while invalid, record after shrinking. Works with sums of non-negative numbers, counts of distinct values, «at most k replacements»…

  • Shortest run that reaches a target

    When: «The smallest slice whose total is at least X», «the shortest substring that contains all of these letters».

    Mirror image: grow until the window becomes valid, then shrink while it stays valid, recording the length at every step of the shrink. The answer may not exist: start from «infinity» and return a sentinel.

  • Window with a map of counts

    When: The rule is about what's inside, not about a sum: «no repeats», «at most two distinct products».

    Keep a map value → count. Entering increments; leaving decrements and deletes the key at zero, so map.size is the number of distinct values. Memory becomes O(k).

  • Maximum of every window

    When: «For each block of k, report its maximum» — a sum won't do because you can't «subtract» a maximum.

    Keep a deque of indices whose values are decreasing. Pop from the back anything smaller than the new value, pop from the front anything that has left the window. Still O(n): each index enters and leaves the deque once.

Common mistakes

What usually goes wrong and how to avoid it.

  • Avoid

    Using a window when the values can be negative

    Better

    With negatives, adding an element can make the sum go down, so shrinking no longer means «getting closer to valid». Switch to prefix sums plus a map (or a sorted structure) and say why.

  • Avoid

    Writing if instead of while when shrinking

    Better

    A single big element can require several removals. With if the window stays invalid and you record a wrong answer. Use while and trust the amortised cost.

  • Avoid

    Recomputing the summary inside the loop

    Better

    Summing the window with slice(...).reduce(...) at every step brings back O(n·k). Update the summary incrementally: add on the right, subtract on the left.

  • Avoid

    Off-by-one on the length

    Better

    With inclusive edges the length is right - left + 1. Run your code by hand on a two-element input before claiming it works.

  • Avoid

    Forgetting to clean up the map

    Better

    If counts drop to zero but the key stays, size lies about how many distinct values are inside. Delete the key when its count reaches zero.

How to recognise it

Clues in a problem statement that call for it.

  • The words «contiguous», «consecutive», «in a row», «substring» or «subarray».
  • «The longest…» or «the shortest…» run that satisfies a condition.
  • «Every block of k» or «within a window of k» — a moving average, a rolling total.
  • A brute-force solution that tries every start and every end and recomputes the inside each time.
  • A rule that only gets harder to satisfy as the run grows (a total under a cap, no repeats, at most k of something).

Common questions

Short answers to the usual doubts.

Why is it O(n) if there's a loop inside a loop?

Because the inner loop doesn't restart. Over the whole execution, left moves forward at most n times in total, so the inner loop's body runs at most n times altogether. Add the n iterations of the outer loop and you get about 2n steps. Saying «amortised» and explaining that both pointers only move forward is exactly what the interviewer wants to hear.

What's the difference between this and two pointers?

A sliding window is a special case of two pointers: both move in the same direction and what matters is everything between them. In the classic two-pointer problems (a palindrome, a pair in a sorted array) the pointers usually start at opposite ends and only the two elements they point at matter.

What if they ask for the run itself, not just its length?

Store the edges whenever you improve the best: bestLeft = left; bestRight = right. At the end, slice the input once. It doesn't change the complexity.

How do I handle negative numbers, then?

Use prefix sums: the total of a run is prefix[right + 1] - prefix[left]. For «a run that adds up to exactly X», a map from prefix sum to earliest index finds it in O(n). For «at least X» with negatives you need a monotonic deque over the prefix sums. Naming the limitation is worth more than the fix.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.