NeetCode 150, stage 3: Sliding Window

← Two Pointers · All 150 problems · Stack →

A window is a range [left, right] that moves across a slice or a string. This stage trains you to keep a small state for the window and to update it in O(1) when an item enters or leaves. That update removes the inner loop, so O(n²) becomes O(n).

Garden notes: the Go syntax for this stage.

Problems on this page

Templates to memorize

Template A: Best so far in one pass

Signal

The problem asks for the best pair of two positions, with the first before the second: buy, then sell. For each position, the best earlier partner is one value, such as the lowest value before it.

// TEMPLATE A: best so far in one pass.
// For each item, the best earlier partner is one value: the lowest value
// before it.
func bestGain(nums []int) int {
    if len(nums) == 0 {
        return 0
    }
    lowest := nums[0] // the lowest value before the current item
    best := 0
    for _, x := range nums {
        // 1. RECORD: pair x with the best earlier value
        best = max(best, x-lowest)
        // 2. UPDATE the earlier value for the next items
        lowest = min(lowest, x)
    }
    return best
}

The moves are RECORD, then UPDATE. Record first, so the earlier value always comes from a position before the current one. This is a window whose left side jumps to the best start.

Say it

“For each day I only need the lowest price before it. I keep that minimum while I scan, so it is one pass, O(n) time and O(1) space.”

Template B: Variable window, longest

Signal

The problem asks for the longest substring or subarray that obeys a rule: no repeat, at most K replacements, at most K different values.

// TEMPLATE B: variable window, longest. The window is nums[left..right].
// Here the rule is "no value appears two times".
func longestValidWindow(nums []int) int {
    count := make(map[int]int) // the state of the window
    best, left := 0, 0
    for right := 0; right < len(nums); right++ {
        count[nums[right]]++ // 1. GROW: nums[right] enters
        // 2. SHRINK while the window breaks the rule
        for count[nums[right]] > 1 {
            count[nums[left]]--
            left++
        }
        // 3. RECORD: the window is valid here
        best = max(best, right-left+1)
    }
    return best
}

The moves are GROW, SHRINK, then RECORD. Shrink with a for loop until the window obeys the rule again. Record after the shrink, when the window is valid. Each index enters one time and leaves one time, so the two loops together cost O(n).

Say it

“I grow the window to the right, and when it breaks the rule I shrink it from the left until it is valid again. Each index enters and leaves once, so the time is O(n).”

Template C: Fixed window

Signal

The problem gives the size of the window, or the size is the length of a word. Examples are a permutation of a word, an anagram in a text, and each window of size K.

// TEMPLATE C: fixed window of size k. One item enters, one item leaves.
func maxWindowSum(nums []int, k int) int {
    best := math.MinInt
    sum := 0 // the state of the window
    for right := 0; right < len(nums); right++ {
        sum += nums[right] // 1. ADD the item that enters
        if right >= k {
            sum -= nums[right-k] // 2. REMOVE the item that leaves
        }
        if right >= k-1 { // 3. CHECK only when the window is full
            best = max(best, sum)
        }
    }
    return best
}

The moves are ADD, REMOVE, then CHECK. The item that leaves is at index right-k. Check only when the window is full, that is from right = k-1. For letter counts, the state is a [26]int array, and == compares two arrays.

Say it

“The window has a fixed size, so each step adds one item and removes one item. I update the state in O(1) and I never recount the window.”

Template D: Shortest window with a need counter

Signal

The problem asks for the minimum window that contains all the required items.

// TEMPLATE D: shortest window that contains all the required values.
// It returns the length of that window, or 0 when no window has them all.
func shortestCover(nums []int, required []int) int {
    // need[x] > 0: the window still needs x that many times
    need := make(map[int]int)
    for _, x := range required {
        need[x]++
    }
    // how many required items the window still needs
    missing := len(required)
    best, left := 0, 0
    for right := 0; right < len(nums); right++ {
        if need[nums[right]] > 0 { // 1. GROW: this item fills a need
            missing--
        }
        need[nums[right]]-- // below 0: the window has more than it needs
        for missing == 0 {  // the window is valid
            if best == 0 || right-left+1 < best {
                best = right - left + 1 // 2. RECORD each valid window
            }
            need[nums[left]]++ // 3. SHRINK: nums[left] leaves
            if need[nums[left]] > 0 {
                missing++ // the window needs that value again
            }
            left++
        }
    }
    return best
}

The moves are GROW, then RECORD and SHRINK while the window is valid. This is the opposite of Template B: the record is inside the shrink loop, because each valid window is a candidate. The integer missing tells in O(1) if the window is valid, so you never compare two count tables.

Say it

“I count what I need, and one integer tells me how many items the window still lacks. When it reaches zero I record the window and shrink it from the left, so the time is O(m + n).”

Template E: Monotonic deque

Signal

The problem asks for the maximum or the minimum of each window, in O(n).

// TEMPLATE E: monotonic deque. It holds indexes. Their values decrease from
// front to back, so the front is the maximum of the window.
func windowMaximums(nums []int, k int) []int {
    res := []int{}
    deque := []int{}
    for right := 0; right < len(nums); right++ {
        // 1. POP BACK: a value that is not larger than the new one cannot
        // win again
        for len(deque) > 0 && nums[deque[len(deque)-1]] <= nums[right] {
            deque = deque[:len(deque)-1]
        }
        deque = append(deque, right) // 2. PUSH BACK the new index
        // 3. POP FRONT: that index left the window
        if deque[0] <= right-k {
            deque = deque[1:]
        }
        if right >= k-1 { // 4. RECORD when the window is full
            res = append(res, nums[deque[0]])
        }
    }
    return res
}

The moves are POP BACK, PUSH BACK, POP FRONT, then RECORD. Store indexes, not values. The index tells you when the front is out of the window. Use <= in the pop at the back, so equal values do not collect in the deque.

Say it

“I keep a deque of indexes with decreasing values, so the front is the maximum of the window. A new value removes the smaller ones behind it, because they can never be the maximum again, and the total time is O(n).”

Mistakes in this stage

  • len(s) counts bytes and s[i] is a byte. A byte window is correct for ASCII input only.
  • The size of the window is right - left + 1. Without the + 1, each answer is one too small.
  • An array such as [26]int compares with ==. A slice or a map does not compile with ==.
  • deque[0] on an empty slice panics. In Template E the push comes before the read of the front, so the deque is never empty there.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

121. Best Time to Buy and Sell Stock

LeetCode 121 · Easy

3. Longest Substring Without Repeating Characters

LeetCode 3 · Medium

424. Longest Repeating Character Replacement

LeetCode 424 · Medium

567. Permutation in String

LeetCode 567 · Medium

76. Minimum Window Substring

LeetCode 76 · Hard

239. Sliding Window Maximum

LeetCode 239 · Hard


← Two Pointers · All 150 problems · Stack →