Skip to main content
LeetCode Prep
CHAPTER 06 Beginner

Sliding Window Problems

Updated: May 18, 2026
5 min read

# 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 the left 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 window K 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.

python
12345678910111213
def findMaxAverage(nums, k):
    # 1. Initialize the first window
    window_sum = sum(nums[:k])
    max_sum = window_sum
    
    # 2. Slide the window
    for i in range(k, len(nums)):
        # Add the new element entering the right, subtract the old element leaving the left
        window_sum = window_sum + nums[i] - nums[i - k]
        max_sum = max(max_sum, window_sum)
        
    return max_sum / k
# Time: O(N), Space: O(1)

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. 1. Expand the window by moving right and adding elements.
  1. 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 left until the condition becomes valid again.
  1. 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.

java
123456789101112131415161718
public int lengthOfLongestSubstring(String s) {
    HashSet<Character> window = new HashSet<>();
    int left = 0, maxLength = 0;
    
    for (int right = 0; right < s.length(); right++) {
        // Condition broken: We found a duplicate!
        while (window.contains(s.charAt(right))) {
            // Shrink the window from the left until the duplicate is gone
            window.remove(s.charAt(left));
            left++;
        }
        // Expand the window
        window.add(s.charAt(right));
        maxLength = Math.max(maxLength, right - left + 1);
    }
    return maxLength;
}
// Time: O(N), Space: O(K) where K is the alphabet size

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. 1. Expand right, adding to currentsum.
  1. 2. while currentsum >= target:
  1. 3. Record the length (right - left + 1). This might be the shortest!
  1. 4. Shrink left, subtracting from currentsum, to see if we can make the subarray even shorter while still hitting the target.
  1. 5. Return the minimal length found.

8. Common Mistakes

  • Calculating Length Incorrectly: The number of elements in a window from left to right is right - left + 1 (inclusive). Forgetting the + 1 is the most common off-by-one error in interviews.
  • Using an if instead of a while: In a variable window, when a condition is broken, you cannot just move left once. You must use a while loop to continuously move left until 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 max
length. Memorizing this template prevents panic.

10. Exercises

  1. 1. Trace the variable window for Longest Substring Without Repeating Characters on the string "pwwkew". What happens when right hits the second 'w'?
  1. 2. In a fixed-size window, why don't we use a nested loop to sum the window every time it moves?

11. MCQs

Question 1

What specific keyword in an interview prompt should immediately make you think of the Sliding Window technique?

Question 2

How does the Sliding Window technique achieve O(N) Time Complexity when calculating the sum of multiple subarrays?

Question 3

In a Fixed-Size Sliding Window problem, how do the left and right pointers move?

Question 4

In a Variable-Size Sliding Window problem, what dictates when the window should expand or shrink?

Question 5

When calculating the length (number of elements) inside a window bounded by index left and index right (inclusive), what is the correct math?

Question 6

In the "Longest Substring Without Repeating Characters" problem, what data structure is best paired with the Sliding Window to track duplicates?

Question 7

What is a common mistake when shrinking a Variable-Size window?

Question 8

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?

Question 9

Is the Sliding Window technique applicable to Unsorted arrays?

Question 10

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 length k." (LeetCode 1456).

15. FAQs

  • Q: Is Sliding Window just another name for Two Pointers?
A: It is a *subset* of Two Pointers. All Sliding Windows use Two Pointers, but not all Two Pointers are Sliding Windows.

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 length K 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.

17. Next Chapter Recommendation

We have mastered horizontal iteration. But what if we need to process data in a specific order, like "Last-In, First-Out"? In Chapter 7: Stack and Queue Problems, we will explore LIFO and FIFO data structures, essential for parsing strings and evaluating expressions.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·