728 × 90 — Top Banner Ad
DSA Pattern Guide

🪟 Sliding Window Pattern

From beginner to advanced — learn every Sliding Window technique used in FAANG interviews with real LeetCode problems and working code.

4
Sub-patterns
28
Problems
O(n)
Typical Time
★★★
Interview Freq.

🪟 What Is the Sliding Window Pattern?

The Sliding Window pattern is a technique that processes a contiguous subarray or substring by maintaining a "window" that slides across the data structure. Instead of recomputing the result for each new window from scratch — which costs O(n·k) — you incrementally update by removing the element that left and adding the element that entered, achieving O(n) time complexity.

It is one of the most frequently tested patterns in FAANG interviews, appearing in problems related to subarrays, substrings, stream data, and optimization under constraints.

Core Intuition

Think of it as a physical window on a train. As the train moves, the window reveals a new slice of the scenery while the old one disappears — you never see the whole landscape, just the current "window."

🎯 When to Use Sliding Window

Recognize these signals in a problem statement to reach for the sliding window technique:

  • The problem involves a contiguous subarray or substring
  • You need to find a maximum, minimum, longest, or shortest subarray/substring
  • The problem mentions a fixed window size k or a constraint (at most k distinct, sum ≥ target)
  • A brute-force solution is O(n²) and you need to optimize to O(n)
  • The problem involves character frequencies or counts in a window
When NOT to use it

Sliding Window requires the data to be linear (array or string) and the window to be contiguous. It does not apply to non-contiguous subsets, tree paths, or graph traversals.

🔬 The 4 Sliding Window Sub-patterns

1. Fixed Window
Window size k is constant. Slide by removing left and adding right on every step.
Max avg subarray of size k
2. Variable Window
Window expands until a constraint is violated, then shrinks from the left.
Longest substring ≤ k distinct chars
3. Monotonic Deque
Track max/min inside the window using a double-ended queue (deque).
Sliding Window Maximum (#239)
4. Frequency Matching
Compare character frequency maps of window vs target using a match counter.
Minimum Window Substring (#76)

Pattern 1: Fixed-Size Window

The window size never changes. Initialize the window for the first k elements, then slide right by adding one element and removing one.

⏱ Time: O(n) 💾 Space: O(1)
PythonFixed Window Template
def fixed_window(arr, k):
    # Build the initial window
    window_sum = sum(arr[:k])
    result = window_sum

    for i in range(k, len(arr)):
        # Slide: add new right element, remove old left element
        window_sum += arr[i] - arr[i - k]
        result = max(result, window_sum)

    return result

Classic problems: 643. Maximum Average Subarray I, 346. Moving Average from Data Stream

Pattern 2: Variable-Size Window

Expand the right pointer unconditionally. When the constraint is violated, shrink from the left until the constraint is restored. The answer is tracked throughout.

⏱ Time: O(n) 💾 Space: O(k)
PythonVariable Window Template
def variable_window(s, k):
    from collections import defaultdict
    freq = defaultdict(int)
    left = 0
    result = 0

    for right in range(len(s)):
        freq[s[right]] += 1           # expand window

        while len(freq) > k:           # constraint violated
            freq[s[left]] -= 1
            if freq[s[left]] == 0:
                del freq[s[left]]
            left += 1                   # shrink from left

        result = max(result, right - left + 1)

    return result

Classic problems: 3. Longest Substring Without Repeating Characters, 904. Fruit Into Baskets, 209. Minimum Size Subarray Sum

Pattern 3: Monotonic Deque (Max/Min in Window)

When you need the maximum or minimum of the current window in O(1), maintain a deque of indices whose values form a decreasing (for max) or increasing (for min) sequence. Remove elements outside the window and smaller/larger elements that are no longer useful.

⏱ Time: O(n) 💾 Space: O(k) Hard
PythonMonotonic Deque Template — LC #239 Sliding Window Maximum
from collections import deque

def maxSlidingWindow(nums, k):
    dq = deque()        # stores indices, values are decreasing
    result = []

    for i, num in enumerate(nums):
        # Remove indices outside window
        if dq and dq[0] < i - k + 1:
            dq.popleft()

        # Remove smaller elements (they'll never be the max)
        while dq and nums[dq[-1]] < num:
            dq.pop()

        dq.append(i)

        if i >= k - 1:
            result.append(nums[dq[0]])  # front is always the max

    return result

Pattern 4: Frequency Matching Window

Progress:
0 / 5

Used when the window must contain all characters of a target string (possibly with extra characters). Track a "formed" count — how many characters in the window have met their required frequency. When formed equals the number of unique characters in target, you have a valid window.

⏱ Time: O(n + m) 💾 Space: O(n + m) Hard
PythonFrequency Matching — LC #76 Minimum Window Substring
from collections import Counter

def minWindow(s, t):
    need = Counter(t)
    have, total = 0, len(need)
    window = {}
    res, res_len = [-1, -1], float("inf")
    left = 0

    for right in range(len(s)):
        window[s[right]] = window.get(s[right], 0) + 1
        if s[right] in need and window[s[right]] == need[s[right]]:
            have += 1

        while have == total:
            if (right - left + 1) < res_len:
                res, res_len = [left, right], right - left + 1
            window[s[left]] -= 1
            if s[left] in need and window[s[left]] < need[s[left]]:
                have -= 1
            left += 1

    l, r = res
    return s[l:r+1] if res_len != float("inf") else ""
In-Feed Ad · 728 × 90

📋 All Sliding Window LeetCode Problems

22 curated problems across 3 sub-patterns. Start with Fixed Window, progress to Variable and Monotonic Deque.

💡 Interview Tips & Common Mistakes

Tip #1 — Identify the constraint first

Before coding, ask: "What defines a valid window?" Is it the size (fixed), a sum (variable), or a character count (frequency)? The constraint determines the pattern.

Tip #2 — The "at most k" trick

Problems asking for subarrays with exactly k distinct values can be solved as: f(exactly k) = f(at most k) − f(at most k−1). This converts "exact" constraints to "at most" which is easier to window.

Common Mistake — Off-by-one on window size

Remember: window size = right − left + 1. When shrinking, increment left before computing the new window size. Always verify your template on the example case before submitting.

Common Mistake — Forgetting to update result inside the while loop

In some problems, the optimal window occurs while you are shrinking, not just after expanding. Update the result inside both the expansion and shrinkage phases when needed.

In-Feed Ad 2 · 728 × 90

🗺️ Explore More DSA Patterns

👉 Two Pointers
Two Pointers Pattern Guide →
🧮 Dynamic Programming
11 patterns · 35 problems →
🕸️ Graph Algorithms
8 patterns · 53 problems →
📄 Resume Checker
Analyze for ATS & interviews →
Track All 368 Problems → Analyze Your Resume →

Sliding Window FAQ

What is the Sliding Window pattern in LeetCode?

The Sliding Window pattern maintains a contiguous subarray or substring as a "window" that slides through the data. It reduces time complexity from O(n²) to O(n) by incrementally updating the window result — adding the entering element and removing the leaving element — instead of recomputing from scratch.

When should I use a fixed vs variable sliding window?

Use a fixed window when the problem specifies an exact window size k (e.g., "maximum average subarray of size k"). Use a variable window when the window size changes based on a constraint (e.g., "longest substring with at most k distinct characters"). The key difference is whether the window size is given or derived.

What is the time complexity of Sliding Window?

Most Sliding Window algorithms run in O(n) time because each element is added to and removed from the window at most once. Space complexity is typically O(1) for fixed windows or O(k) for windows using a hash map to track element frequencies, where k is the number of distinct elements.

What are the most important Sliding Window problems to practice?

The five must-solve problems are: Minimum Window Substring (hard — frequency matching), Longest Substring Without Repeating Characters (medium — variable window), Sliding Window Maximum (hard — monotonic deque), Longest Repeating Character Replacement (medium — maxCount trick), and Fruit Into Baskets (medium — at most k distinct). Master these and you can handle any sliding window interview question.

How is Sliding Window different from Two Pointers?

Both use two indices, but with different semantics. Sliding Window always operates on a contiguous subarray/substring between left and right pointers, focusing on the window contents. Two Pointers are more general — the pointers can move independently, toward each other, or at different speeds (fast & slow), and don't always define a contiguous window.

🔗 Related Guides & Resources