CS concepts

Sliding Window Explained: Every Variant Interviewers Ask

Updated Dec 4, 2026 · 3 min read

A sliding window keeps two edges over a stretch of a string or array. The right edge grows it, the left edge shrinks it, and because both only move forward, every element enters once and leaves once, so the scan is O(n). Longest-window problems shrink when the rule breaks, shortest-window problems shrink while the rule still holds, and negative numbers break the idea, which is when you switch to prefix sums.

Sliding Window Variants reel cover

Key points

  • ●Fixed window: add the element walking in, subtract the one walking out.
  • ●Longest window (LeetCode 3): shrink from the left when the rule breaks.
  • ●Shortest window (LeetCode 209): shrink while the rule still holds, saving each length.
  • ●LeetCode 424: a window is fine while its length minus its top letter count is at most k.
  • ●Negative numbers break sum windows. Use prefix sums and a hash map instead.
Step-by-step visual sheet: Sliding Window Variants
The full visual sheet, made with Edithly.Open the interactive sheet

Why a window beats checking every stretch

Take a string of 10,000 letters and ask for the longest stretch with no repeated letter. Checking every stretch means about 50 million substrings. A sliding window gets there in at most 20,000 steps, because each letter walks into the window once and walks out once.

A window is two edges over things that sit in a row. The right edge grows it. The left edge shrinks it. You spot these problems by their wording: substring, subarray or "in a row", plus a rule the stretch must follow. The same two edges solve six different problem shapes, and they differ only in when the left edge moves.

Fixed size: add one, drop one

Biggest sum of 3 in a row in [2, 1, 5, 1, 3, 2]? Sum the first three (8), then slide: add the number walking in, subtract the one walking out. The sums go 8, 7, 9, 6, so the answer is 9 (5, 1 and 3).

s = sum(nums[:k])
best = s
for i in range(k, len(nums)):
    s += nums[i] - nums[i - k]
    best = max(best, s)
return best

Permutation in String (LeetCode 567) is the same move with letter counts instead of a sum.

Longest and shortest: the one word that changes

For the longest substring with no repeats (LeetCode 3) on "abcabcbb", grow right until a letter repeats, then drop letters from the left until the old copy is gone. The window never gets past 3, so the answer is 3, "abc".

For the shortest run with a sum of at least 7 (LeetCode 209) in [2, 3, 1, 2, 4, 3], the logic flips: shrink while the window still works, saving the length each time. The windows that reach 7 shrink from length 4 to 3 to 2, ending on [4, 3]. The dry-run box on the visual sheet above traces each of those moments.

left, total, best = 0, 0, float('inf')
for right, x in enumerate(nums):
    total += x
    while total >= target:
        best = min(best, right - left + 1)
        total -= nums[left]
        left += 1
return 0 if best == float('inf') else best

A window with k changes

LeetCode 424 gives "AABABBA" and one allowed change. Ask each window how many letters you'd have to change: its length minus the count of its most common letter. "AABA" needs 4 - 3 = 1 change, so it's allowed, and no window of 5 is. The answer is 4. The top count never goes down when you shrink, and that's fine: a smaller top can never give a longer answer.

Minimum Window Substring

LeetCode 76 is the hard one: the shortest part of "ADOBECODEBANC" that holds an A, a B and a C. Keep a count of what you need and a single number for how many are still missing. Grow right until nothing is missing, then shrink left while nothing is missing, saving the shortest. The first cover is "ADOBEC" (6 letters), and the answer is "BANC" (4).

need = Counter(t)
missing = len(t)
left, best = 0, ""
for right, ch in enumerate(s):
    if need[ch] > 0:
        missing -= 1
    need[ch] -= 1
    while missing == 0:
        if not best or right - left + 1 < len(best):
            best = s[left:right + 1]
        need[s[left]] += 1
        if need[s[left]] > 0:
            missing += 1
        left += 1
return best

That one counter is what keeps it at O(len(s) + len(t)).

The stock problem is a window too

In Best Time to Buy and Sell Stock (LeetCode 121) the left edge is the buy day and the right edge is the sell day. When today's price is lower than the buy day, the left edge jumps straight to today. For prices 7, 1, 5, 3, 6, 4 the best profit is 5: buy at 1, sell at 6.

The trap: negative numbers

Every sum window bets that adding a number raises the sum and dropping one lowers it. Negative numbers break that bet. With [-1, 4] and a target of at least 4, the window sees -1 and then 3, and reports no answer, while the 4 alone works. Before you slide, check that the numbers are all positive and that the problem says "in a row". With negatives, use prefix sums and a hash map instead.

Frequently asked questions

How do I know a problem wants a sliding window?

Look for two things in the statement: the answer is a stretch in a row (a substring, a subarray, consecutive days) and the stretch has to follow a rule, like no repeated letters, a sum of at least a target, or at most k changes. If the items can be skipped, as in a subsequence, it is not a window.

Why is a sliding window O(n) when it has a while loop inside a for loop?

The left edge only ever moves forward, and it can't pass the right edge. So across the whole run it moves at most n times in total, and the right edge moves n times. That's at most 2n steps, which is O(n). For a string of 10,000 letters that's at most 20,000 steps instead of about 50 million substrings.

What is the difference between the longest and shortest window templates?

One word. For the longest window you shrink when the window breaks the rule, then record the length. For the shortest window you shrink while the window still satisfies the rule, recording the length before each shrink, because every shrink is a chance at a shorter answer.

Why doesn't a sliding window work with negative numbers?

The window assumes that adding a number makes the sum bigger and dropping one makes it smaller. With [-1, 4] and a target of at least 4, the window sums -1 and then 3 and never reaches 4, even though the 4 alone works. For sums with negatives, use prefix sums with a hash map, as in LeetCode 560.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free