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

Time Complexity: O(n)

Space Complexity: O(1)

Sliding Window

intermediate

Maintains a moving subarray window and slides it to avoid recomputing overlapping regions; O(n).

2
[0]
1
[1]
5
[2]
1
[3]
3
[4]
2
[5]
4
[6]
1
[7]
Window [0..2]:sum = 8.Max so far:8.New max!
Current window
Best window
Outside window
First window [0..2], sum = 8. Max sum = 8.