Sliding Window Problems
# CHAPTER 6
Sliding Window Problems
1. Chapter Introduction
The Sliding Window pattern is an extension of the Two Pointer technique. While standard Two Pointers look at two individual elements, a Sliding Window looks at a continuous *chunk* (subarray) of elements between theleft and right pointers. Whenever an interview question asks for the "longest," "shortest," or "maximum/minimum" of a continuous subarray or substring, the Sliding Window is almost always the required optimal O(N) solution.
2. The Core Concept
Imagine a physical window frame placed over an array.Array: [1, 3, -1, -3, 5, 3, 6, 7]
If the window size is 3, you sum [1, 3, -1]. To move the window to the right, you do NOT recalculate the sum of the new window [3, -1, -3] from scratch.
*The Trick:* You take the old sum, subtract the element that fell out of the left side (1), and add the new element that entered the right side (-3).
This reduces nested loop recalculations, turning O(N^2) into O(N).
3. Pattern 1: Fixed-Size Window
The size of the windowK never changes. The pointers left and right move together in lockstep.
*Use Cases:* Find the max sum subarray of size K. Find the moving average of size K.
*Example: Maximum Average Subarray I*
*Prompt:* Find a contiguous subarray whose length is equal to K that has the maximum average value.
4. Pattern 2: Variable-Size Window (The Classic)
The size of the window grows and shrinks dynamically based on a specific condition. *The Rules:*-
1.
Expand the window by moving
rightand adding elements.
-
2.
If the window breaks the condition (e.g., the sum gets too large, or we find a duplicate character), we shrink the window by moving
leftuntil the condition becomes valid again.
- 3. Update the max/min answer at the end of each valid step.
*Example: Longest Substring Without Repeating Characters (LeetCode #3)*
*Prompt:* Given a string s, find the length of the longest substring without repeating characters.
5. String Anagram Windows
Problems like "Find All Anagrams in a String" require a fixed-size window over a string, paired with a Frequency Map. You maintain an array of 26 integers representing the character counts of your current window. As the window slides, you increment the right character count and decrement the left character count, comparing it to the target anagram map in O(1) time.6. Real-World Scenario: Rate Limiting
The sliding window is not just a theoretical interview trick. It is the core algorithm used in API Gateway Rate Limiting (e.g., the "Sliding Window Log" algorithm). If an API limits a user to 100 requests per minute, a sliding window of timestamps moves forward every second, dropping requests older than 60 seconds and preventing abuse.7. Mini Project: Shortest Subarray >= Target
*Prompt:* Find the minimal length of a contiguous subarray of which the sum >= target. *The Logic:*-
1.
Expand
right, adding tocurrentsum.
-
2.
while currentsum >= target:
-
3.
Record the length (
right - left + 1). This might be the shortest!
-
4.
Shrink
left, subtracting fromcurrentsum, to see if we can make the subarray even shorter while still hitting the target.
- 5. Return the minimal length found.
8. Common Mistakes
-
Calculating Length Incorrectly: The number of elements in a window from
lefttorightisright - left + 1(inclusive). Forgetting the+ 1is the most common off-by-one error in interviews.
-
Using an
ifinstead of awhile: In a variable window, when a condition is broken, you cannot just moveleftonce. You must use awhileloop to continuously moveleftuntil the window is valid again.
9. Best Practices
- Standard Template: Always structure your variable window code the same way:
for right in array: -> update state -> while invalid: -> shrink left -> update maxlength. Memorizing this template prevents panic.
10. Exercises
-
1.
Trace the variable window for
Longest Substring Without Repeating Characterson the string "pwwkew". What happens whenrighthits the second 'w'?
- 2. In a fixed-size window, why don't we use a nested loop to sum the window every time it moves?
11. MCQs
What specific keyword in an interview prompt should immediately make you think of the Sliding Window technique?
How does the Sliding Window technique achieve O(N) Time Complexity when calculating the sum of multiple subarrays?
In a Fixed-Size Sliding Window problem, how do the left and right pointers move?
In a Variable-Size Sliding Window problem, what dictates when the window should expand or shrink?
When calculating the length (number of elements) inside a window bounded by index left and index right (inclusive), what is the correct math?
In the "Longest Substring Without Repeating Characters" problem, what data structure is best paired with the Sliding Window to track duplicates?
What is a common mistake when shrinking a Variable-Size window?
What happens to the Time Complexity if you use a nested loop to calculate the sum of a window of size K every time it moves forward one space?
Is the Sliding Window technique applicable to Unsorted arrays?
How does learning the standard Sliding Window "template" help in an interview?
14. Interview Questions
-
Q: "Given an array of integers and an integer
k, return the maximum number of vowels in any substring of lengthk." (LeetCode 1456).
15. FAQs
- Q: Is Sliding Window just another name for Two Pointers?
16. Summary
The Sliding Window is the undisputed king of "contiguous subarray" problems. Use a Fixed-Size window when the prompt gives you an exact lengthK and asks for an aggregate (sum/average). Use a Variable-Size window when the prompt gives you a condition (no duplicates, sum < target) and asks for the longest/shortest length. Memorize the while(invalid) { shrink left } template to prevent bugs.