roadmap/Sliding Window

Topic 3 / 16

Sliding Window

EasyArray~3 days
Easy to grasp
progress0 / 12 solved

Maintain a dynamic contiguous window to solve subarray/substring problems in O(n).

Maintain a dynamic window over a contiguous subarray or substring using two pointers. Expand the right pointer to grow the window; move the left pointer to shrink it when a constraint is violated. This avoids recomputing overlapping subarrays, reducing O(nยฒ) nested loops to O(n).

  • โ—†Longest or shortest subarray/substring with a constraint
  • โ—†Fixed window size k โ€” sum, max, average
  • โ—†Problems with 'at most k distinct', 'without repeating', 'exactly k'
  • โ—†Any optimization over contiguous elements
Fixed-size window
Slide a window of exactly k elements; maintain a running aggregate.
Variable-size window (max)
Expand right freely; shrink left when constraint breaks.
Variable-size window (min)
Shrink left aggressively once constraint is satisfied.
Window with frequency map
Track character/element counts inside the window using a HashMap.
Sliding window โ€” fixed size k=3
2
0
1
1
5
2
1
3
3
4
2
5
6
6
4
7
window[0..2]
โ†’
sum = 8
step 1 / 6
Brute force
Generate all subarrays, check each one โ†’ O(nยฒ) or O(nยณ) for strings.
Observation
Adjacent subarrays share most of their elements. Slide instead of restarting.
Optimization
Two pointers: right expands the window, left shrinks when the constraint is violated. Track state (sum/count/map) incrementally.
Final complexity
O(n) โ€” each element enters and exits the window exactly once.

When should you shrink the left side of a sliding window?

What is the time complexity of a well-implemented sliding window?

For a fixed-size window of k, how do you update the window as it slides?

Check each question you can answer confidently before moving to the next topic.

Progress is saved on this device