programmingconcepts

§ 3.4 · Algorithms

Sliding window

Keep a window over neighbouring values and slide its edges forward, updating a running total instead of starting over.

The sliding window technique looks at a run of neighbouring values, the window, and moves its edges forward instead of recomputing from scratch. Adding a value on the right and removing one on the left each cost O(1), so problems about subarrays or substrings, like the shortest run with a given sum, take O(n) instead of O(n²).

Time
O(n)
Extra space
O(1)
Works on
Neighbouring runs (subarrays)
Each pointer
Only moves right
Requires
Two pointersArrays
def shortest_window(a, target):
    """Length of the shortest run of neighbours summing to at least target.
    Values must be positive. Returns 0 if no run is long enough."""
    best = 0
    total = left = 0
    for right in range(len(a)):
        total += a[right]
        while total >= target:
            if best == 0 or right - left + 1 < best:
                best = right - left + 1
            total -= a[left]
            left += 1
    return best

Find the shortest run of neighbours that adds up to at least 16. The window starts empty at the left.

step 0 / 0in the windowjust addedshortest window

Fig. 3.4. Blue cells are inside the window and orange is the value just added. At the end, the shortest window that reaches the target turns black.

Intuition

Say you want the sum of every 3 neighbouring values in [4, 2, 9, 7, 5]. Adding each run of 3 from scratch repeats work: 2 + 9 gets added twice. Instead, keep a running total. When the window slides one step right, add the value coming in and subtract the one going out. Each step costs two operations, however wide the window is.

That’s the whole technique. The window is a range left..right, and you never rebuild it, only slide its edges.

Fixed and variable windows

  • Fixed size: the window is always k wide. Slide both edges together: add a[right], subtract a[right − k]. Used for moving averages, and for “maximum sum of k neighbours”.
  • Variable size: the window grows and shrinks to meet a condition. The figure shows this kind. It’s used for “shortest run with a sum of at least S” and “longest substring with no repeated letter”.

How the variable window works

To find the shortest run of neighbours that adds up to at least a target:

  1. Move right forward one step and add its value to the sum. The window grows.
  2. While the sum reaches the target, record the window’s length if it’s the shortest so far, then shrink it: subtract a[left] and move left forward.
  3. Repeat until right reaches the end.
def shortest_window(a, target):
    """Length of the shortest run of neighbours summing to at least target.
    Values must be positive. Returns 0 if no run is long enough."""
    best = 0
    total = left = 0
    for right in range(len(a)):
        total += a[right]
        while total >= target:
            if best == 0 or right - left + 1 < best:
                best = right - left + 1
            total -= a[left]
            left += 1
    return best

Why it’s O(n)

There are two loops, but right moves forward n times in total, and left can only follow behind it, so it also moves at most n times in total. Neither pointer ever moves back. That’s at most 2n pointer moves, which is O(n). The “pointer moves” counter in the figure never goes above twice the size.

Checking every start and end instead is O(n²), and recomputing each sum on top of that is O(n³).

Where it shows up

Problem Window
Maximum sum of k neighbours Fixed, size k
Moving average of the last k readings Fixed, size k
Shortest subarray with sum ≥ S Variable, shrink while the sum is ≥ S
Longest substring without repeating characters Variable, shrink while there’s a repeat (keep a set or hash map)
Smallest window containing all given letters Variable, with letter counts

Common mistakes

  1. Recomputing the sum each step. That throws away the whole point. Keep a running total.
  2. Shrinking with if instead of while. One new value can let several old ones go.
  3. Using it with negative values. Shrinking assumes the sum drops when a value leaves. With negatives, it can rise.

Check yourself

Check yourself

In [2, 3, 1, 2, 4, 3], what's the shortest run with a sum of at least 7?

Check yourself

Why is the variable window O(n) even though there's a loop inside a loop?

Sources

  • Steven Halim and Felix Halim, Competitive Programming 3 (2013), “Sliding Window.”
  • LeetCode problem 209, “Minimum Size Subarray Sum.”

Newsletter

One new concept each week, by email.

Signup opens soon.