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. 1.Maximum Average Subarray I
    easy
  2. 2.Maximum Sum Subarray of Size K
    easy
  3. 3.Minimum Size Subarray Sum
    medium
  4. 4.Longest Substring Without Repeating Characters
    medium
  5. 5.Longest Repeating Character Replacement
    medium
  6. 6.Permutation in String
    medium
  7. 7.Find All Anagrams in a String
    medium
  8. 8.Minimum Window Substring
    hard
  9. 9.Max Consecutive Ones III
    medium
  10. 10.Fruit Into Baskets
    medium
  11. 11.Subarray Product Less Than K
    medium
  12. 12.Grumpy Bookstore Owner
    medium
  13. 13.Maximum Points You Can Obtain from Cards
    medium
  14. 14.Sliding Window Maximum
    hard

Also Important

8 more questions worth practicing.

  1. 15.Contains Duplicate II
    easy
  2. 16.Number of Sub-arrays of Size K and Average ≥ Threshold
    medium
  3. 17.Minimum Recolors to Get K Consecutive Black Blocks
    easy
  4. 18.Longest Subarray of 1's After Deleting One Element
    medium
  5. 19.Frequency of the Most Frequent Element
    medium
  6. 20.Binary Subarrays With Sum
    medium
  7. 21.Count Number of Nice Subarrays
    medium
  8. 22.Minimum Operations to Reduce X to Zero
    medium

How to Think

  1. Continuous part of array/string?Sliding Window
  2. Fixed size K?Add new item, Remove old item
  3. Longest / shortest valid substring?Expand right, Shrink left
  4. Need no duplicates?Sliding Window + Hash Set / Hash Map
  5. Need character frequency?Window + Frequency Map
  6. 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 Answer

Main 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.

Visual Memory Rule
        EXPAND
L ─────────────→ R

Invalid?
   ↓
Move L →

Valid again?
   ↓
Continue R →

💡 Golden Rule: "Right explores. Left removes what makes the window invalid."

Interview Rules

  1. 1. Continuous array/string? → Think Sliding Window
  2. 2. Size exactly K? → Fixed Window
  3. 3. Longest valid? → Expand + Shrink
  4. 4. Smallest valid? → Expand until valid, then shrink
  5. 5. Duplicate characters? → Window + Map/Set
  6. 6. Character count? → Window + Frequency Map
  7. 7. Maximum of every K? → Monotonic Deque
  8. 8. Avoid recalculating the full window
  9. 9. Left and right usually move only forward
  10. 10. Most standard sliding-window solutions are O(n)

Small Rules

  1. Rule 1: Works with continuous elements, not random elements.
  2. Rule 2: Fixed window size right - left + 1 = K.
  3. Rule 3: Variable window: Expand right, when invalid shrink left.
  4. Rule 4: Do not recalculate everything (O(n × k) bad → O(n) good).
  5. Rule 5: A nested while does 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 MaxSliding 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."