Arrays · Core Array Techniques

Sliding Window

Maintaining a running window over a contiguous range so it does not need to be rescanned from scratch on every step.

  • 5 min read
  • 10 practice questions
  • 4 graded problems
On this page
  1. Description
  2. The approach (fixed-size window)
  3. A second flavor: variable-size windows
  4. Where you'll see it
  5. Which tool for which job?
  6. Common mistakes
  7. Check yourself
  8. Key takeaways
  9. Quick revise
  10. Practice

Description

A sliding window is a contiguous range of an array or string that moves forward one step at a time. It carries a running summary of what's inside it: a sum, a count, or a map of how often each value appears. Instead of recomputing that summary for every range, you add the element that enters and remove the one that leaves. It answers "best contiguous range" questions, such as the largest sum of k values in a row, the longest substring without repeats, or the shortest subarray that reaches a target.

We'll go from simple to more technical:

  1. The fixed-size window: one add and one subtract per step.
  2. The variable-size window: right always advances, left catches up.
  3. Where the same idea runs in production (rate limiters, moving averages).
  4. When it applies, and the mistakes that make the window drift.

The approach (fixed-size window)

The brute force adds up every window from scratch: k additions for each of the n - k + 1 windows, O(n*k) in all. But two neighboring windows share all but two elements. So keep one running sum. Each step adds the element that enters on the right and, once the window is full, subtracts the one that leaves on the left.

The largest sum of 3 values in a row in [3, 1, 4, 2, 5, 1]:

iEntersLeavesWindowSumBest
03[3]3
11[3, 1]4
24[3, 1, 4]88
323[1, 4, 2]78
451[4, 2, 5]1111
514[2, 5, 1]811

Java

int windowSum = 0;
for (int i = 0; i < nums.length; i++) {
    windowSum += nums[i];
    if (i >= k) windowSum -= nums[i - k];   // drop the element leaving the window
    if (i >= k - 1) best = Math.max(best, windowSum);
}

Python

window_sum = 0
for i in range(len(nums)):
    window_sum += nums[i]
    if i >= k:
        window_sum -= nums[i - k]    # drop the element leaving the window
    if i >= k - 1:
        best = max(best, window_sum)

The window is never rescanned. Each step does one add and, once the window is full, one subtract. That turns O(n*k) into O(n).

A second flavor: variable-size windows

Some questions have no fixed size. "The shortest subarray with a sum of at least the target" needs a window that grows and shrinks:

Java

int left = 0, sum = 0, best = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right++) {
    sum += nums[right];                    // right always advances
    while (sum >= target) {                // left advances only while the condition holds
        best = Math.min(best, right - left + 1);
        sum -= nums[left];
        left++;
    }
}

Python

left = total = 0
best = float("inf")
for right in range(len(nums)):
    total += nums[right]                  # right always advances
    while total >= target:                # left advances only while the condition holds
        best = min(best, right - left + 1)
        total -= nums[left]
        left += 1

right moves one step per loop, as before. left moves zero, one or several steps, as long as the window still meets the condition. So the two edges no longer move together. For [1, 4, 2, 2, 5, 1] and a target of 7, the shortest window is [2, 5], of length 2. Each element enters once and leaves at most once, so this is still O(n).

Where you'll see it

A rate limiter works this way. "How many requests in the last 60 seconds?" is a window over a stream of timestamps, updated as requests arrive instead of recounted each time. A dashboard's rolling 5-minute average latency is computed the same way, without rereading the whole buffer every tick.

Which tool for which job?

You needUse
Something about every window of exactly k elementsa fixed-size window
The shortest or longest range meeting a conditiona variable-size window
A subarray sum with negative numbers allowedprefix sums with a hash map (next skill)
The maximum or minimum of every windowa monotonic deque
The median of every windowtwo heaps (O(log k) per step)
"Exactly K" of somethingat most K minus at most K - 1

Common mistakes

MistakeWhat happensDo this instead
i > k instead of i >= kone element is never removed; every answer is offtrace k = 1 by hand
A set where duplicates can be in the windowremoving one copy forgets the othersa frequency map: decrement, delete at 0
Shrinking a sum window when values can be negativeanswers are missedprefix sums instead
A plain variable for the window maximumwrong once the max leavesa monotonic deque
if instead of while when shrinkingthe window stays invalidshrink in a loop until it's valid

Check yourself

Try to answer before opening each one - recalling beats re-reading.

1. A fixed-size window checks i > k instead of i >= k. What goes wrong?

Show answer

The subtraction due at i = k, which removes nums[0], never happens. Later steps subtract nums[1], nums[2] and so on as usual, but nums[0] stays in the sum forever. From i = k on, every sum is the right window's sum plus a stale nums[0].

2. Why can't a variable-size window move left by a fixed amount when the window stops meeting the condition?

Show answer

How far left must move depends on the data. One step may not be enough, and a fixed bigger step can skip past the best window. So left moves one step at a time in its own loop, checking the condition after each step.

3. You need the maximum of every window of size k. Can it be updated cheaply as the window slides?

Show answer

Not with a plain variable. When the maximum leaves the window, you'd have to rescan to find the next one. A monotonic deque fixes that: it keeps only the values that could still become the maximum, in decreasing order, for amortized O(1) per step. Some summaries need a smarter structure before they can slide.

Key takeaways

  • A fixed-size window adds the element that enters and subtracts the one that leaves: O(n) instead of O(n*k).
  • In a variable-size window, right moves every step and left moves only while the window still meets the condition.
  • The most common bug is an off-by-one at the window's edge. Trace k = 1 by hand.
  • Whatever you did when an element entered, undo exactly when it leaves (decrement a count, don't just remove from a set).
  • The idea only pays off when the summary can be updated more cheaply than recomputed.

Quick revise

The whole skill on one page, for the night before an interview.

Everything from the lesson and the deep dive on one page. Skim it before practice or an interview, and open the full lesson for anything that doesn't ring a bell.

Pick the tool

You needUse
Every window of size ka fixed window: add one, remove one
Shortest / longest range meeting a conditiona variable window
Subarray sums with negativesprefix sums
Max or min of every windowa monotonic deque
Median of every windowtwo heaps, lazy deletion
Exactly Kat most K minus at most K - 1

Snippets worth knowing by heart

Java

int left = 0, best = 0;
Map<Character, Integer> count = new HashMap<>();
for (int right = 0; right < s.length(); right++) {
    count.merge(s.charAt(right), 1, Integer::sum);            // enter
    while (count.size() > k) {                                // shrink until valid
        char out = s.charAt(left++);
        if (count.merge(out, -1, Integer::sum) == 0) count.remove(out);   // undo exactly
    }
    best = Math.max(best, right - left + 1);
}

Python

left = best = 0
count = {}
for right, ch in enumerate(s):
    count[ch] = count.get(ch, 0) + 1          # enter
    while len(count) > k:                     # shrink until valid
        out = s[left]
        left += 1
        count[out] -= 1                       # undo exactly
        if count[out] == 0:
            del count[out]
    best = max(best, right - left + 1)

The traps

  • i > k instead of i >= k: one element is never removed, so every answer is off. Trace k = 1 by hand.
  • A set where a frequency map is needed: removing one copy forgets the others. Decrement counts, delete at 0.
  • Negative numbers in a shrinking sum window: shrinking no longer lowers the sum, so answers are missed. Use prefix sums.
  • A plain variable for the window maximum: it's wrong once the max leaves. Use a monotonic deque.
  • if instead of while when shrinking: the window stays invalid. Shrink in a loop until it's valid.

Staff-level points, one line each

  • Each element enters and leaves once: O(n) despite the nested loop.
  • i > k turned 3, 5, 7, 9 into 3, 6, 8, 10.
  • Shrinking needs a monotonic condition: [-2, 4], target 3, found nothing.
  • Monotonic deque: 199,994 operations vs 98.9 million comparisons (n = 100,000, k = 1,000).
  • Exactly K = at most K - at most (K - 1): 698 = the brute force.
  • Window median: two heaps, O(n log k).
  • A running float sum drifted 2.5e-09 over 2 million slides - recompute or use integers.

Say it in an interview

  • "Neighboring windows share all but two elements, so I add one and remove one."
  • "right always advances; left catches up while the window is invalid."
  • "Each element enters and leaves once, so it's O(n)."
  • "With negatives the window condition isn't monotonic, so I'd use prefix sums."

Practice

This skill comes with 10 multiple-choice questions that tell you which misconception a wrong answer reveals and 4 graded problems. Your answers are graded and your mastery is tracked, so you'll know when the skill holds up. Running code and saving progress need a free account.

Practice Sliding Window free

Maximum Sum Subarray of Size K

MediumProCoding problemJava · Python

Given an array of integers nums and an integer k, find the largest total of any k consecutive elements.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Longest Substring Without Repeating Characters

MediumProCoding problemJava · Python

Find the longest stretch of consecutive characters in a string s in which no character appears twice, and return its length.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Minimum Size Subarray Sum

MediumProCoding problemJava · Python

You have a list of positive integers nums and a goal target. Find the shortest run of consecutive elements whose total reaches at least target, and return its length. If even the whole list falls short, return 0.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Longest Substring with At Most K Distinct Characters

MediumProCoding problemJava · Python

Given a lowercase string s and a number k, find the longest stretch of consecutive characters that uses no more than k different letters, and return its length.

The full statement, the examples and the hidden test suite are part of AI Proof Engineers Pro.

Practice Sliding Window free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime