Pattern #6
Sliding Window
Important interview questions, thinking patterns, window types, and rules for solving sliding window problems in Go.
Must Solve
14 core questions — solve these first.
- 1.Maximum Average Subarray IFixed K sumeasy
- 2.Maximum Sum Subarray of Size KFixed window slideeasy
- 3.Minimum Size Subarray SumShrink left when validmedium
- 4.Longest Substring Without Repeating CharactersSet/Map + shrink leftmedium
- 5.Longest Repeating Character ReplacementFreq map + maxFreqmedium
- 6.Permutation in StringFixed K freq matchmedium
- 7.Find All Anagrams in a StringFixed K freq mapmedium
- 8.Minimum Window SubstringFreq map + required matchhard
- 9.Max Consecutive Ones IIIAt most K zerosmedium
- 10.Fruit Into BasketsAt most 2 distinct elementsmedium
- 11.Subarray Product Less Than KProduct windowmedium
- 12.Grumpy Bookstore OwnerFixed window boostmedium
- 13.Maximum Points You Can Obtain from CardsTotal sum - fixed windowmedium
- 14.Sliding Window MaximumMonotonic Dequehard
Also Important
8 more questions worth practicing.
- 15.Contains Duplicate IIWindow size K seteasy
- 16.Number of Sub-arrays of Size K and Average ≥ ThresholdFixed K sum checkmedium
- 17.Minimum Recolors to Get K Consecutive Black BlocksFixed K min whiteeasy
- 18.Longest Subarray of 1's After Deleting One ElementAt most 1 zeromedium
- 19.Frequency of the Most Frequent ElementSort + window costmedium
- 20.Binary Subarrays With SumAtMost(K) - AtMost(K-1)medium
- 21.Count Number of Nice SubarraysAtMost(K) odd numbersmedium
- 22.Minimum Operations to Reduce X to ZeroMax window sum = Total - Xmedium
How to Think
- Continuous part of array/string?Sliding Window
- Fixed size K?Add new item, Remove old item
- Longest / shortest valid substring?Expand right, Shrink left
- Need no duplicates?Sliding Window + Hash Set / Hash Map
- Need character frequency?Window + Frequency Map
- Need max/min for every window?Sliding Window + Monotonic Deque
Go Thinking & Reference
Typical Fixed Window Shape
func maxSumFixed(nums []int, k int) int {
sum, maxSum := 0, 0
for right := 0; right < len(nums); right++ {
sum += nums[right]
if right >= k {
sum -= nums[right-k]
}
if right >= k-1 && sum > maxSum {
maxSum = sum
}
}
return maxSum
}👉 Time: O(n) | Space: O(1)
Typical Variable Window Shape
func lengthOfLongestSubstring(s string) int {
m := make(map[byte]int)
left, maxLen := 0, 0
for right := 0; right < len(s); right++ {
m[s[right]]++
for m[s[right]] > 1 { // invalid state
m[s[left]]--
left++
}
if curLen := right - left + 1; curLen > maxLen {
maxLen = curLen
}
}
return maxLen
}👉 Time: O(n) | Space: O(min(m, n))
General Mental Model
Add Right
↓
Invalid?
↓
Remove Left
↓
Update AnswerMain Sliding Window Types
1. Fixed Window
Window size never changes. (e.g. Find maximum sum of 3 continuous numbers in [2, 1, 5, 1, 3, 2]).
┌─────────┐
2 1 5 1 3 2
└─────────┘
┌─────────┐
2 1 5 1 3 2
└─────────┘Rule: newSum = oldSum - outgoing + incoming
Fixed K → slide one step.
2. Variable Window
Window grows and shrinks dynamically. (e.g. Longest substring without repeating characters).
a b c a b c
↑ ↑
L R → [a b c] (Valid ✅)
a b c a b c
↑ ↑
L R → [a b c a] (Invalid ❌ → move L until valid: a [b c a])Rule: Right expands. Left fixes.
EXPAND
L ─────────────→ R
Invalid?
↓
Move L →
Valid again?
↓
Continue R →💡 Golden Rule: "Right explores. Left removes what makes the window invalid."
Interview Rules
- 1. Continuous array/string? → Think Sliding Window
- 2. Size exactly K? → Fixed Window
- 3. Longest valid? → Expand + Shrink
- 4. Smallest valid? → Expand until valid, then shrink
- 5. Duplicate characters? → Window + Map/Set
- 6. Character count? → Window + Frequency Map
- 7. Maximum of every K? → Monotonic Deque
- 8. Avoid recalculating the full window
- 9. Left and right usually move only forward
- 10. Most standard sliding-window solutions are
O(n)
Small Rules
- Rule 1: Works with continuous elements, not random elements.
- Rule 2: Fixed window size
right - left + 1 = K. - Rule 3: Variable window: Expand right, when invalid shrink left.
- Rule 4: Do not recalculate everything (
O(n × k)bad →O(n)good). - Rule 5: A nested
whiledoes NOT mean O(n²) if left and right only move forward.
Production Thinking
Recent Activity (e.g. 5 min window) → remove old ← add new →
Rate Limiting (e.g. 100 req / 60s) → moving window of timestamps
System Monitoring (e.g. 5 min CPU avg) → maintain current running window
Streaming Data Max → Sliding Window + Monotonic Deque
Remember This
Fixed K → Add right → Remove left → Slide
Longest valid → Expand right → Invalid? → Shrink left
Substring → Think window
Duplicates → Window + Set/Map
Frequency → Window + Map
Max every K → Window + Deque💡 Golden Rule: "Expand with right. Fix the window with left."