ALGORITHMS · 16  /  SLIDING WINDOW

The Moving Frame.

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.

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?

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.

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 / 17 Algorithms done

Explore the topic

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

More Algorithms