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.
window (characters inside)
1def longest_unique(s):2 inside = set()3 left = best = 04 for right, ch in enumerate(s):5 while ch in inside:6 inside.remove(s[left])7 left += 18 inside.add(ch)9 best = max(best, right - left + 1)10 return best
Variables
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
Two pointers
Put two indices in the array and move them by a rule so that every move rules out many candidates at once. Checking all pairs is O(n²); two pointers does it in one pass, O(n), with no extra memory.
8 min read →Frequency counting
Walk the input once and keep a count per value in a hash map (or an array of 26 for letters). Comparing or querying counts replaces sorting and nested loops: O(n) time, O(k) space for k distinct values.
7 min read →Prefix sums
Build `prefix[i]` = sum of the first i numbers in O(n). Then the sum of `nums[l..r]` is `prefix[r+1] − prefix[l]`: O(1) per question instead of O(n).
7 min read →