sagelearnai

Sliding Window

Signal: a contiguous subarray or substring, plus "longest", "shortest", "at most k", "contains all of", or a fixed window size k.

Core idea: instead of recomputing every window from scratch (O(n·k) or O(n²)), maintain the window's state as you add the element entering on the right and remove the element leaving on the left. Each index enters and leaves once, so the total is O(n).

Two templates

python
# Variable-size window: longest window satisfying a condition
l = 0
state = ...                              # counts, sum, set...
for r, x in enumerate(a):
    add(x, state)                        # expand right
    while not valid(state):              # shrink until valid again
        remove(a[l], state); l += 1
    best = max(best, r - l + 1)

# Fixed-size window of length k
for r, x in enumerate(a):
    add(x)
    if r >= k: remove(a[r - k])
    if r >= k - 1: record(window)

For "shortest window that satisfies X", flip it: expand until valid, then shrink while still valid, recording the minimum each time.

When sliding windows fail

The shrink step relies on monotonicity: shrinking a window must never make an invalid window valid in a way you'd miss. With negative numbers, "subarray sum ≥ k" breaks this. Use prefix sums + a monotonic deque or a hash map instead (see Prefix Sums).

Problems

  1. Best Time to Buy and Sell Stock (Easy): Track the minimum price so far
  2. Maximum Average Subarray I (Easy): Fixed window running sum
  3. Longest Substring Without Repeating Characters (Medium): Window + last-seen index map
  4. Longest Repeating Character Replacement (Medium): Window valid iff length − maxFreq ≤ k
  5. Permutation in String (Medium): Fixed window of len(s1); compare counts
  6. Find All Anagrams in a String (Medium): Fixed window of len(p) with letter counts
  7. Minimum Size Subarray Sum (Medium): Expand right; shrink left while sum ≥ target
  8. Subarray Product Less Than K (Medium): Window with product < k; each r adds r − l + 1 subarrays
  9. Fruit Into Baskets (Medium): Longest window with at most 2 distinct values
  10. Sliding Window Maximum (Hard): Monotonic decreasing deque of indices
  11. Minimum Window Substring (Hard): Expand until valid, shrink while valid
  12. Max Consecutive Ones III (Medium): Longest window containing at most k zeros
  13. Longest Subarray of 1's After Deleting One Element (Medium): Window with at most one zero; answer is window − 1
  14. Get Equal Substrings Within Budget (Medium): Window over per-index costs |s[i]−t[i]| with sum ≤ budget
  15. Grumpy Bookstore Owner (Medium): Base satisfied + best fixed window of recovered customers
  16. Number of Substrings Containing All Three Characters (Medium): For each r, count valid starts = smallest window start that still has a, b, c