Algorithms Playbook
PatternTime O(n) · Space O(k)9 min read

Sliding window: the best subarray or substring in one pass

Keep a range [left, right] that grows on the right and shrinks on the left. Fixed and variable windows, the template, and why the inner while loop is still O(n).

In short

For questions about a contiguous subarray or substring, keep a window: grow it on the right, and shrink it from the left only when it breaks the rule. Each element enters and leaves once: O(n) instead of checking all O(n²) ranges.

The idea: don't restart, slide

Checking every substring means O(n²) windows, each re-scanned. But consecutive windows overlap almost completely: moving one step only adds one element on the right and drops one on the left. Update what you know instead of recomputing it.

Sliding window: longest substring without repeating characters
String
Speed
0a1b2c3a4b5c6b7bleft

window (characters inside)

{ }
1def longest_unique(s):
2 inside = set()
3 left = best = 0
4 for right, ch in enumerate(s):
5 while ch in inside:
6 inside.remove(s[left])
7 left += 1
8 inside.add(ch)
9 best = max(best, right - left + 1)
10 return best
The window is empty. right will grow it one character at a time; left will shrink it only when needed.

Variables

left0
right—
best0
Step 1/32· Pointer moves: 0
Grow on the right, shrink on the left only when the window breaks the rule. Both pointers only move forward, so the nested-looking while loop is still O(n) overall.

Fixed and variable windows

Fixed size k

  • Max sum of any k consecutive numbers
  • Add nums[right], subtract nums[right − k]
  • Average of every window of size k

Variable size

  • Longest substring without repeats
  • Smallest subarray with sum ≥ target
  • Longest substring with at most K distinct characters
left = 0
for right in range(len(s)):
    add(s[right])                 # grow
    while window_is_invalid():
        remove(s[left])           # shrink
        left += 1
    update_answer(left, right)

Why the while loop doesn't make it O(n²)

It looks like a loop inside a loop, but left only ever moves forward and never past right. Across the whole run, left moves at most n times in total. So the total work is at most 2n pointer moves: O(n). Say this in the interview; it's a classic follow-up question.

How to recognise it

  • The words contiguous, subarray or substring.
  • Longest / shortest / maximum something that satisfies a condition.
  • A window of size k moving over the input.
  • Counts of what's inside the window (often a hash map or an array of 26).

Key takeaways

  • 01A window [left, right] grows on the right and shrinks on the left.
  • 02Each element enters and leaves once: O(n), even with the inner while.
  • 03Fixed windows slide by one; variable windows shrink until valid again.
  • 04It needs a monotonic rule; with negative sums, use prefix sums instead.

Check your understanding

1 of 3

Which keyword most strongly suggests a sliding window?

Related topics