Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

ALGORITHMS · 16  /  SLIDING WINDOW

The Moving Frame.

Watch the explainer

Which three neighbours add up highest? The lazy way re-adds every window from scratch. The smart way keeps a running total and, as the frame slides, just subtracts what left and adds what entered — the whole array in one O(n) pass.

THE GIST · 20 SECONDS

The sliding window answers "best contiguous run of k" without redoing work. Sum the first k elements once. Then slide: each step, subtract the element leaving the window and add the one entering — the sum updates in O(1). Track the best as you go. Adjacent windows overlap in k−1 elements, so re-summing them is pure waste.

  • Windowk consecutive cells
  • Enter+ the new right element
  • Leave− the old left element
  • O(n)one pass, not n×k

Hit Step to slide the frame one cell — or Play and watch it glide across, keeping the best sum without re-adding a thing.

UNDER THE HOOD

What you just played, written down

The trick is noticing what stays the same. Two neighbouring windows share all but two elements — so throw away one, take in one, and never re-add the middle.

How the sliding window thinks — four moves

  1. Sum the first window once. Add elements 0 … k−1. That is your starting window sum and your first best.
  2. Slide by one. The window moves right: element i−k falls out of the left, element i enters on the right.
  3. Update in O(1). sum += arr[i] − arr[i−k]. No loop — one add, one subtract, whatever k is.
  4. Track the best. After each slide, if sum > best, remember it. When the window reaches the end, best is your answer.
WHY BRUTE FORCE WASTES SO MUCH

Re-summing each window adds up all k elements every time — and adjacent windows overlap in k − 1 of them. You re-add the same middle numbers over and over. The window just remembers the total instead.

The whole thing in code

def max_sum(arr, k):
    if len(arr) < k:
        return None
    # sum the first window once
    window = sum(arr[:k])
    best = window
    # slide: drop the left, add the right
    for i in range(k, len(arr)):
        window += arr[i] - arr[i - k]
        if window > best:
            best = window
    return best
TIMEO(n)vs O(n·k) naive
SPACEO(1)just the running sum
FIXED VS VARIABLE WINDOWS

This is a fixed window — always k wide. A variable window uses two pointers that grow and shrink on a condition, for "longest substring without repeats" or "smallest subarray summing to ≥ S."

⚠ Max in a window is trickier

A running sum updates in O(1), but a running maximum can't — removing the leaving element might remove the max. The sliding-window maximum keeps a monotonic deque to still hit O(n).

↔ Two pointers

The sliding window is a special two-pointer pattern where left and right bound a range. Variable windows move them independently; fixed windows keep them a constant k apart.

★ Where it's used

Moving averages, longest-substring problems, smallest-subarray-with-sum, rate limiting over a time window, and streaming stats over recent data.

The picture: each window is the last one, adjusted

21513271sum 8sum 7 = 8 − 2 + 1sum 9 = 7 − 1 + 3sum 6 = 9 − 5 + 2sum 12 = 6 − 1 + 7sum 10 = 12 − 3 + 1
The array [2, 1, 5, 1, 3, 2, 7, 1] with k = 3. Each bar is one window and carries its sum. Only the first is added from scratch (2 + 1 + 5); every other bar is its neighbour above, minus the element that fell off the left and plus the one that came in on the right. The highlighted window, [4..6] with elements 3, 2, 7, is the best.

Worked example, step by step

Take arr = [2, 1, 5, 1, 3, 2, 7, 1] and k = 3. The first window is summed in full. After that each step is window += arr[i] − arr[i−k], followed by a comparison with best.

StepWindowUpdatewindowbest
0[0..2]2 + 1 + 588
1[1..3]8 − 2 + 178
2[2..4]7 − 1 + 399
3[3..5]9 − 5 + 269
4[4..6]6 − 1 + 71212
5[5..7]12 − 3 + 11012

The row with sum 6 is worth noticing. At step 3 the window slides from [2..4] to [3..5] by dropping a 5 and picking up a 2, and the sum falls from 9 to 6, but best keeps 9: the window follows the data, best remembers the peak. The biggest jump, from 6 to 12 at step 4, comes from a single large entering element (7) replacing a small leaving one (1). The final window [5..7] adds only 1 and loses a 3, so it ends at 10. The answer is 12, from the window [3, 2, 7]. Summing all six windows from scratch adds 18 terms; the sliding version does 3 + 5 × 2 = 13 operations. The gap is small at k = 3 and grows with k.

Complexity and trade-offs

CaseTimeSpaceWhy
Sliding window (fixed size)O(n)O(1)One add and one subtract per step, whatever k is.
Re-sum every windowO(n·k)O(1)Adjacent windows share k − 1 elements and each is added again.
Prefix sumsO(n) build, O(1) per queryO(n)Window sum is P[i+1] − P[i+1−k]; works for any window, not only sliding ones.
Window maximum with a monotonic dequeO(n)O(k)Each index is pushed once and popped at most once.
Variable window (two pointers)O(n) amortisedO(1) to O(alphabet)Left and right each move forward only, never back.

On an array of 100,000 values with k = 1,000, re-summing every window did 99,001,000 additions; the sliding sum did 199,000 additions and subtractions, and both found the same best sum, 3,003. The ratio is about k/2, so the gain grows with the window size. For a variable window the cost is bounded by pointer movement: scanning a random lowercase string of 100,000 characters for the longest stretch with no repeated letter, the right pointer moved 100,000 times and the left pointer 99,994 times, under 2n in total even though there is a loop inside a loop. The trade-off is what the window can remember. A sum is easy to undo (subtract it); a maximum is not, which is why that case needs the extra deque and O(k) space.

Common mistakes

  • Not guarding the short array

    With arr = [1, 2] and k = 3, sum(arr[:3]) quietly sums what exists and the function returns 3, for a window that does not exist. Check len(arr) < k first and return None (or raise).

  • Subtracting the wrong element

    The leaving element is arr[i − k]. Writing arr[i − k + 1] subtracts something still inside the window. On the array above that returned 11 instead of 12.

  • Starting best at 0

    For [-3, -1, -2] with k = 2 the best window sums to −3, but a best = 0 start returns 0. Initialise best to the first window's sum (or negative infinity).

  • Treating a maximum like a sum

    A running maximum can only grow; it cannot forget the element that left. For [5, 1, 1, 1, 1, 4] with k = 3 the running-maximum version prints 5, 5, 5, 5 while the true window maxima are 5, 1, 1, 4. Use a monotonic deque of indices.

  • Letting floating-point error accumulate

    A running sum keeps its history. For [1e16, 1, 1, 1, 1] with k = 2, the first slide adds 1 − 1e16, which rounds, and the next three windows are reported as 0, 0, 0 although each true sum is 2. With floats of very different sizes, recompute the window now and then or sum with integers.

Where this shows up

  • Moving averages and monitoring

    A moving average over the last k readings, and "count of events in the last k seconds", are fixed windows: add the new reading, drop the one that aged out. Metrics dashboards and alert rules use exactly this.

  • Rate limiting

    A sliding-window rate limiter keeps the requests from the recent past and counts them against a limit, dropping the old ones as time advances. It is the same enter-and-leave bookkeeping applied to timestamps.

  • String problems

    Longest substring without repeating characters, smallest substring containing all required letters and longest run with at most k changes are variable windows: grow on the right until a condition breaks, shrink from the left until it holds again.

  • Network and stream processing

    Windowed aggregations over a stream (the last minute of requests, the last 100 events) are computed incrementally this way, so the cost per event stays constant instead of growing with the window.

SOLVE IT YOURSELF

Solve it: max sum of k consecutive

This one is yours to write — in Python or TypeScript, running for real in your browser. Keep a running sum and slide it. Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement max_sum(arr, k): return the maximum sum of any k consecutive elements of arr. Use a sliding window so the whole thing runs in O(n). If the array is shorter than k, return None.

HINTS — 4 IDEAS
  1. Sum the first k elements once; call it window, and set best = window.
  2. For i from k to the end: window += arr[i] - arr[i-k] — add the entering, subtract the leaving.
  3. After each slide, update best = max(best, window).
  4. Never re-loop over the window — that's what makes it O(n) instead of O(n·k).
CPython · WebAssembly
QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. When the window slides one step right, how does the sum update?

    Answer: Subtract the element that left and add the element that entered — Adjacent windows overlap in k-1 elements, so you only adjust for the two that changed: sum += arr[i] - arr[i-k]. That is O(1) per slide.

  2. Why is the sliding window O(n) instead of O(n·k)?

    Answer: Because each slide is O(1), done about n times — Summing the first window is O(k), then each of the ~n slides costs O(1). Total is O(n), versus re-summing every window at O(k) each for O(n·k).

  3. For which of these does a running-sum sliding window NOT directly work in O(1) per slide?

    Answer: Maximum ELEMENT in each k-window — A sum (and thus average) updates in O(1). A running maximum can’t: if the leaving element was the max, you’d have to rescan. The sliding-window maximum needs a monotonic deque to stay O(n).

FAQ

Sliding window, answered

What is the sliding window technique?

A way to process every contiguous window of an array efficiently by reusing overlap. For a fixed size k, keep a running sum and, on each slide, subtract the leaving element and add the entering one — turning O(n·k) into O(n).

Why is it O(n)?

Adjacent windows share k−1 elements, so each slide is just one subtraction and one addition — O(1) — done n−k times. Total O(n), versus re-summing each window at O(n·k).

Fixed vs variable window?

Fixed: always k wide, slides one step (max sum of k). Variable: two pointers grow/shrink on a condition (longest substring without repeats, smallest subarray with sum ≥ S).

When can I use it?

When you need something about contiguous subarrays and the tracked quantity — a sum, count, or frequency — can be updated incrementally as the window moves.

Where is it used?

Moving averages, longest/smallest subarray problems, character-frequency substring problems, rate limiting over a time window, and streaming statistics.

WATCH IT EXPLAINED

Prefer a video walkthrough?

Six minutes: the brute force, its cost, the repeated work, the running total, the trade-offs against prefix sums, and the follow-up questions an interviewer asks next.

RESULT

—

Next → let the two edges move independently on a condition and you get the variable window — the pattern behind "longest substring without repeating characters."

Finished this one? 0 / 99 Algorithms done
NextThe Running Total: Prefix Sums Next on the “Two pointers and a window” ladder · rung 4 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms

Explore more