Sliding Window
Grow and shrink a contiguous range while keeping a running total or count.
- inside the window
- active this step
- removed / popped
- ruled out
Grow to “abc”
No repeats yet, so the window grows to length 3.
VARIABLES
- left
- 0
- right
- 2
- window
- "abc"
- best
- 3
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Two indices bound a window over an array or string. The right edge grows the window; the left edge shrinks it when the window breaks a rule.
Why it matters
Updating a running total as the window moves avoids recomputing every subarray - O(n) instead of O(n²).
Think of it like this
A train window: scenery enters on one side as it leaves the other, and you only track what’s in view.
Use it when
- Longest or shortest contiguous subarray or substring meeting a condition
- Fixed-size windows (averages, maximums)
- At most k distinct items or k changes
Avoid it when
- Validity isn’t monotonic - e.g. sums with negative numbers
- The answer needn’t be contiguous (that’s a subsequence)
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Variable-size window | O(n) | O(1) to O(k) |
| Every subarray | O(n²) | O(1) |
| Fixed window of size k | O(n) | O(1) |
Often confused with: prefix sums - they handle range sums with negatives; windows need monotonic validity.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Positive numbers make “shrink while valid” safe
- Character rules usually mean a count map inside the window
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Moving left backwards when the repeat is outside the window - check last[ch] >= left
- Recomputing the window’s total from scratch each step
- Using a window when negatives break monotonicity
Edge cases to test
- Empty string - return 0
- One repeated character like "bbbb"
- All characters unique
Knowledge check
Quick check to lock in the intuition.
Why does “shortest subarray with sum ≥ k” break the basic window when negatives are allowed?
Practice
Apply what you just watched on real interview problems.