Stage 1 · Code
Arrays & Strings
Sliding Window
Fixed and variable-size windows for subarray/substring problems.
Fixed Size Window
Sliding Window — size k=3
Step 1 / 7 — First window [0..2] = 8
window [2..4] = 5+1+3 = 9 (maximum)
Window size k is constant. Slide by adding right element, removing left element. Maintain window state (sum, count, frequency). O(n) time.
Variable Size Window
Window expands (right++) until constraint violated, then shrinks (left++) until valid. Used for 'longest/shortest subarray satisfying condition'.
Sliding Window Template
Classic Examples
| Problem | Window Type | State | Key Insight |
|---|---|---|---|
| Max sum subarray size k | Fixed | Sum | Subtract left, add right |
| Min subarray sum ≥ target | Variable | Sum | Shrink when sum ≥ target |
| Longest substring ≤ k distinct | Variable | Char freq map | Shrink when distinct > k |
| Longest substring no repeat | Variable | Char last index | Jump left to last index + 1 |
| Permutation in string | Fixed | Char freq diff | Match target freq |
| Min window substring | Variable | Char freq + count | Shrink when all chars covered |
| Count subarrays sum = k | Variable | Prefix sum + hashmap | Count prefix[j] - prefix[i] = k |
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.