Sliding Window

Maintain a window over a contiguous range and update it incrementally for fixed-size and variable-size subarray and substring problems.

Intermediate · about 7 hours · difficulty 3/5

Learn first: Two Pointers

Sliding window applies when the question asks about a contiguous subarray or substring and the window's validity changes in one direction as it grows.

Two templates

  • Fixed size k: add the new element, remove the one leaving, update the answer (Maximum Average Subarray, max sum of k consecutive elements).
  • Variable size: expand the right end; while the window is invalid, shrink from the left; record the answer. Used for "longest" and "shortest" questions.

Classic problems

Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Minimum Size Subarray Sum, Permutation in String, Find All Anagrams in a String, Fruit Into Baskets, Max Consecutive Ones III, Minimum Window Substring, Sliding Window Maximum (with a monotonic deque).

The counting trick

"Number of subarrays with exactly k distinct" = atMost(k) - atMost(k - 1). The same trick works for "exactly k odd numbers" (Count Number of Nice Subarrays) and Binary Subarrays With Sum.

Pitfalls

  • Using a sliding window when the array has negative numbers and you want a target sum. Shrinking no longer helps; use prefix sums with a hash map.
  • Updating the answer before the window is valid again.
  • Forgetting to decrement counts when the left pointer moves.

You are ready to move on when you can solve Minimum Window Substring and explain why each index enters and leaves the window at most once.

Key concepts

  • Fixed-size window
  • Variable-size window
  • Window with frequency map
  • atMost(k) - atMost(k-1) trick
  • Window maximum with deque
  • When sliding window fails: Negative numbers

Mini project

Solve these 10 in 7 days, log time and pattern: Maximum Average Subarray I, Longest Substring Without Repeating Characters, Minimum Size Subarray Sum, Max Consecutive Ones III, Fruit Into Baskets, Longest Repeating Character Replacement, Permutation in String, Find All Anagrams in a String, Subarrays with K Different Integers, Minimum Window Substring.

Check yourself

Why does the variable sliding window fail for 'count subarrays with sum k' when the array contains negative numbers?

Free resources