Grokking the Coding Interview logo
HomeCoursesBlog
← Back to Blog
Article

Sliding Window Pattern: The Template That Solves 20+ LeetCode Problems

Sliding Window Pattern: The Template That Solves 20+ LeetCode Problems

TL;DR: Sliding window turns "check every subarray" brute force, which is O(n²) or worse, into a single O(n) pass by maintaining a window that slides across the data instead of restarting. There are two templates: fixed-size (window length is given) and variable-size (grow the right edge, shrink the left edge while a constraint is violated). Learn both templates, learn the one-sentence tell for spotting the pattern, and about two dozen common interview problems collapse into fill-in-the-blanks.

This is the first deep dive in our pattern series, and sliding window earned the lead spot for a reason: it's among the most frequently asked patterns at every major company, and it's the clearest demonstration of why patterns beat problem-grinding. Memorize one problem and you know one problem. Learn this template and you can solve Maximum Average Subarray, Longest Substring Without Repeating Characters, Minimum Size Subarray Sum, Max Consecutive Ones III, and twenty more, because they are the same problem in different costumes.

The tell: how to recognize sliding window in an interview

You should suspect sliding window when the problem asks about a contiguous stretch of an array or string, and wants some best or countable property of it:

  • "longest substring that..." / "shortest subarray that..."
  • "maximum sum of any subarray of size k"
  • "count the subarrays that..."
  • "find all anagrams / permutations of X inside Y"

The two words that matter are contiguous (subarray, substring) and an optimization or counting word (longest, shortest, maximum, minimum, count, at most). If the elements don't need to be adjacent, you're likely looking at a different pattern (subsequence problems usually mean DP or two pointers).

Here's why the pattern exists. The brute-force version of these problems checks every possible subarray: two nested loops to pick the boundaries, often a third to evaluate the contents, so O(n²) or O(n³). But consecutive windows overlap almost entirely. The window [i+1 .. j] is the window [i .. j] minus one element. Recomputing it from scratch throws away everything you learned one step earlier. Sliding window keeps the shared state and updates it in O(1) per step, so the whole scan is O(n).

Template 1: fixed-size window

Use this when the problem hands you the window length: "subarray of size k," "every window of k characters."

The idea: compute the first window fully, then slide. Each slide adds the entering element and removes the leaving one.

def max_average_subarray(nums, k):          # LeetCode 643
    window_sum = sum(nums[:k])              # first window
    best = window_sum
    for right in range(k, len(nums)):
        window_sum += nums[right]           # element entering
        window_sum -= nums[right - k]       # element leaving
        best = max(best, window_sum)
    return best / k

One pass, O(n) time, O(1) space. The brute force is O(n·k). That gap is exactly what your interviewer is checking you know.

The state you carry doesn't have to be a sum. For "Maximum Number of Vowels in a Substring of Given Length" it's a vowel count; for "Find All Anagrams in a String" it's a frequency map. The template is identical: add the entering element's contribution, remove the leaving element's contribution, update the answer.

Template 2: variable-size window

This is the one interviews love, because the window size is something you discover, not something you're given: "longest substring without repeating characters," "smallest subarray with sum ≥ target."

The idea: the right edge grows the window one element at a time. Whenever the window becomes invalid (violates the constraint), the left edge shrinks it until it's valid again. Every element enters once and leaves at most once, so it's still O(n) despite the nested-looking loops.

def longest_substring_without_repeats(s):   # LeetCode 3
    seen = set()
    left = 0
    best = 0
    for right in range(len(s)):
        while s[right] in seen:             # window invalid:
            seen.remove(s[left])            # shrink from the left
            left += 1
        seen.add(s[right])
        best = max(best, right - left + 1)
    return best

Read that loop structure again, because it is the pattern:

  1. Expand: right moves forward every iteration, unconditionally.
  2. Shrink: a while loop moves left forward only while the constraint is violated.
  3. Record: update the answer when the window is valid.

For "shortest window" problems (like Minimum Size Subarray Sum), the same skeleton flips: you record the answer inside the shrink loop, because the interesting moment is how small a valid window can get, not how large.

A powerful variation to know: constraints with a budget. "Max Consecutive Ones III" (flip at most k zeros) sounds exotic until you translate it: longest window containing at most k zeros. The window state is one integer (zeros in window), and the shrink condition is zeros > k. Most "at most k" problems reduce this way, and saying that translation out loud in an interview is exactly the pattern-recognition signal hiring committees want to see.

Want the full treatment? Grokking the Coding Interview dedicates an entire chapter to sliding window with 15+ problems solved step by step in six languages, then does the same for all 27 patterns.

The three mistakes that sink candidates

I've watched a lot of sliding window attempts die in interviews, and it's almost always one of these three.

1. Shrinking with if instead of while. One entering element can invalidate the window in a way that takes several removals to fix (think a sum that jumped far past the limit). An if removes one element and moves on with a still-invalid window. This is the single most common sliding window bug; interviewers see it weekly.

2. Recomputing the window instead of updating it. If your code calls sum(nums[left:right+1]) inside the loop, you've rebuilt the O(n²) brute force with extra steps. The entire pattern is incremental state: one add, one remove, per step. If you can't update your state in O(1), that's a sign the window needs a different data structure (a frequency map, a deque), not a rescan.

3. Reaching for it when the data isn't contiguous. Sliding window requires the answer to be a contiguous block, and (for variable windows) the constraint to behave monotonically as the window grows or shrinks. "Longest increasing subsequence" is not a window problem, no matter how much it sounds like one. Part of knowing a pattern is knowing its boundary.

Practice ladder

Solve these in order; each adds exactly one new wrinkle. The first six are the Sliding Window section of Grokking 75.

  1. Maximum Average Subarray I (E): pure fixed-size template.
  2. Maximum Number of Vowels in a Substring of Given Length (M): fixed size, state is a count.
  3. Max Consecutive Ones III (M): variable size with a budget ("at most k zeros").
  4. Longest Subarray of 1's After Deleting One Element (M): the same budget idea, k = 1, with an off-by-one twist.
  5. Minimum Size Subarray Sum (M): variable size, shortest-window flavor (record inside the shrink).
  6. Longest Substring Without Repeating Characters (M): variable size, state is a set/map; the most-asked window problem in interviews.
  7. Stretch goals: Permutation in String (M), Find All Anagrams in a String (M), Longest Repeating Character Replacement (M), and, when you're feeling brave, Minimum Window Substring (H), the final boss of the pattern.

After the ladder, write the tell in your own words ("I should suspect sliding window when ___") and move on. Six to ten problems with the template understood beats thirty solved by copying solutions, which is the whole argument of Why Is LeetCode So Hard?

The takeaway

Sliding window is a single idea, incremental reuse of overlapping work, expressed in two templates. Learn the fixed-size template, learn the expand/shrink/record skeleton, know the tell and the boundary, and a whole category of medium-difficulty interview questions becomes mechanical. That's one pattern down; the field guide to all of them is in our LeetCode patterns overview, and we'll keep going deep on one pattern at a time in this series. Two Pointers is next.

Go deeper: the sliding window chapter in Grokking the Coding Interview walks through every problem in the ladder above with visual explanations and code in Python, Java, JavaScript, C++, C#, and Go. Short on time? Grokking 75 covers the essential six inside a 6-week plan.

FAQs

What is the sliding window pattern in simple terms? It's a way to examine every contiguous chunk of an array or string in one pass. Instead of recomputing each chunk from scratch, you keep a running "window" and update its state in constant time as one element enters on the right and one leaves on the left, turning O(n²) scans into O(n).

How do I know whether to use a fixed or variable window? The problem tells you. If the window length is given ("subarray of size k"), it's fixed. If the question asks for the longest or shortest stretch satisfying a condition, the length is what you're solving for, so it's variable: expand right, shrink left while invalid.

What's the difference between sliding window and two pointers? Sliding window is really a specialization of two pointers where the two indices bound a contiguous range and you maintain state about everything between them. General two-pointer problems (like pair-with-target-sum on a sorted array) move pointers based on comparisons and don't carry window contents. If you're tracking "what's inside," you're doing sliding window.

Why is my sliding window solution O(n) if there's a while loop inside a for loop? Amortized analysis: left only ever moves forward, so across the entire run the inner while loop executes at most n times total, not n times per iteration. Each element enters the window once and leaves at most once. Being able to explain this in an interview is worth as much as the code.

Which sliding window problem is asked most in interviews? Longest Substring Without Repeating Characters is the classic, appearing constantly at Meta, Amazon, and Google. Minimum Window Substring is the standard hard version. If you can solve both and explain the amortized O(n) argument, you're prepared for nearly any window question a loop will throw at you.

One-Stop Portal For Coding Interviews.
Follow us:
Copyright © 2025 Coding Interview All rights reserved.