Sliding Window Visualization & Animation
Maintains a moving subarray window and slides it to avoid recomputing overlapping regions; O(n).
## What is it?
Sliding Window is a technique that maintains a "window" (a contiguous subarray or substring) and slides it across the data structure, adding one element to the right and removing one from the left, to efficiently compute answers without re-scanning overlapping regions.
## How it works
**Fixed-size window:**
- Compute the answer for the first window of size `k`
- Slide: subtract the outgoing element (leftmost) and add the incoming element
- Update the answer at each step
**Variable-size window:**
- Expand the window by moving the right pointer
- Shrink by moving the left pointer when a constraint is violated
- Track the answer (max/min window size) throughout
## When to use
- Maximum/minimum sum subarray of size k
- Longest substring with at most k distinct characters
- Minimum window substring
- Count of subarrays satisfying a constraint
## Key Points
- Converts O(n²) brute-force to O(n) by reusing computation from the previous window
- Fixed-window: single pass; variable-window: two pointers
- Common mistake: forgetting to shrink the window when constraints are violated
Category: algorithms
Difficulty: intermediate
- sliding-window
Time Complexity: O(n)
Space Complexity: O(1)
View Sliding Window Visualization