← All posts

The sliding window, four patterns deep

Turning O(n·k) into O(n) by not throwing away work you already did

Key takeaways
  • When windows overlap, do not rebuild them — update them.
  • The inner while loop is still O(n): left only ever moves forward.
  • Contiguous means window; subsequence does not.

Most array problems have an obvious brute-force answer: check every window, take the best one. It works, and it is O(n·k).

Consecutive windows overlap almost completely. Only one element leaves and one enters. So instead of recomputing, update.

The fixed window

int windowSum = 0;
for (int i = 0; i < k; i++) windowSum += nums[i];

int best = windowSum;
for (int right = k; right < (int)nums.size(); right++) {
    windowSum += nums[right];       // one enters
    windowSum -= nums[right - k];   // one leaves
    best = max(best, windowSum);
}

The right - k index is where this goes wrong most often. When right is the newest element, the oldest sits exactly k positions behind it.

The variable window

When the size is not given — shortest subarray summing to at least target — both edges move. right always advances; left advances only while the window still satisfies the condition.

int left = 0, windowSum = 0, best = INT_MAX;

for (int right = 0; right < (int)nums.size(); right++) {
    windowSum += nums[right];

    while (windowSum >= target) {
        best = min(best, right - left + 1);
        windowSum -= nums[left];
        left++;
    }
}

That inner while looks like it makes this O(n²). It does not — left only moves forward, at most n times across the whole run.

When it does not apply

The shrink-while-valid trick assumes positive values. With negatives, adding an element can decrease the sum, so a failing window might succeed after growing. That needs prefix sums and a deque instead.