Skip to content
Codescope

Sliding window

A range that grows and shrinks instead of being rebuilt.

core10 min8 steps

Before you start

Suppose you want the largest sum of any 3 consecutive elements. The obvious approach recomputes the sum for every starting position — n windows × k additions = O(n·k).

But consecutive windows overlap almost entirely. Sliding from [2,1,5] to [1,5,1] only changes two things: one element leaves the left, one enters the right. Everything in between is unchanged.

So instead of recomputing, **update**: add the entering element, subtract the leaving one. That is O(1) per slide and O(n) overall. The same idea extends to windows that change size to satisfy a constraint.

k = 3, naive

each window summed from scratch — O(n·k)
array
2
lo
1
5
hi
1
3
2

Overlapping windows re-add the same elements over and over.

Step 1 of 8. The naive version recomputes everything. With k = 3, the windows are `[2,1,5]`, `[1,5,1]`, `[5,1,3]`, `[1,3,2]`. Summing each from scratch costs 3 additions apiece. Notice the waste: the values 1 and 5 get added into three different window sums. Nothing is being reused.

01 / 08

Step 01 / 08

The naive version recomputes everything

With k = 3, the windows are [2,1,5], [1,5,1], [5,1,3], [1,3,2]. Summing each from scratch costs 3 additions apiece.

Notice the waste: the values 1 and 5 get added into three different window sums. Nothing is being reused.

sliding-window.cC
/* Max sum of any k consecutive elements. */int max_window(int a[], int n, int k) {    int sum = 0;    for (int i = 0; i < k; i++) sum += a[i];  /* first window */    int best = sum;    for (int i = k; i < n; i++) {        sum += a[i] - a[i - k];   /* add new, drop old — O(1) */        if (sum > best) best = sum;    }    return best;}/* Variable window: longest run summing to <= limit. */int longest_under(int a[], int n, int limit) {    int lo = 0, sum = 0, best = 0;    for (int hi = 0; hi < n; hi++) {        sum += a[hi];                  /* grow right */        while (sum > limit)            sum -= a[lo++];            /* shrink left */        if (hi - lo + 1 > best) best = hi - lo + 1;    }    return best;}