Mental model
A window is a contiguous range [left, right] of the array, together with a summary of what
is inside it: a sum, a count, a frequency table. Sliding the window one step changes it only at
the edges: one value enters on the right, maybe one leaves on the left. If the summary can be
updated from those two values alone, each step costs O(1) instead of re-reading the whole window.
There are two kinds:
- Fixed size. The window always holds exactly
kvalues; every step adds one and removes one. - Variable size. The window grows on the right while it is valid and shrinks from the left when it is not. It is the same-direction two-pointer pattern from the previous lesson, with a running summary attached.
Fixed window: the largest sum of k consecutive values
sum = values[0] + … + values[k-1] # the first window
best = sum, bestStart = 0
for right in k .. n-1:
sum += values[right] - values[right - k] # one enters, one leaves
if sum > best: best = sum, bestStart = right - k + 1
return (best, bestStart)
Recomputing each of the n − k + 1 windows from scratch reads (n − k + 1) · k values, O(n·k).
The sliding version does k additions for the first window and two updates per slide after that:
k + 2(n − k) updates, O(n). The lab prints both numbers; for the Fixed window preset that is
17 updates instead of 24 additions, and the gap grows with k.
A fixed window works with any integers, negative ones included: the size, not the sum, decides
when a value leaves. Ties keep the first window (> rather than ≥), which the shared test
fixture pins down.
Variable window: the longest run with sum ≤ limit
left = 0, sum = 0, best = (start -1, length 0)
for right in 0 .. n-1:
sum += values[right] # expand
while sum > limit: # shrink until valid again
sum -= values[left]; left += 1
if right - left + 1 > best.length: best = (left, right - left + 1)
return best
Invariant (checked after the shrink loop): sum equals the sum of values[left..right], that
sum is ≤ limit, and left is the smallest start for which the run ending at right is valid.
So right − left + 1 is the longest valid run ending at right, and the best over all right is
the answer.
Why the values must be non-negative
Dropping values[left] for good is justified only if no valid run can still start there. With
non-negative values that is guaranteed:
- adding a value never decreases the sum, so if
[left, right]is too big, every longer run[left, right′]withright′ ≥ rightis too big as well:leftcan be discarded for good; - removing a value never increases the sum, so shrinking moves toward validity.
A single negative value breaks both. With limit 3 and values [5, −4, 1], the run [0, 2] sums
to 2 and is valid, but the window drops 5 as soon as it sees sum = 5 > 3 and never reconsiders
it: the algorithm answers 2 instead of 3. The lab rejects negative values in this mode for that
reason; with negative values, use prefix sums (next lesson) or a monotonic deque instead.
The limit itself must be ≥ 0 for the same reason: the empty window has sum 0 and must count as valid so that the shrink loop always stops.
Why it is O(n) despite the nested loop
The while loop sits inside the for loop, but left only ever moves forward and never passes
right + 1. Over the whole run, right advances n times and left advances at most n times, so
the total number of sum updates is at most 2n. The lab's Sum updates metric never exceeds
2 × n; on the Value over the limit preset a single 9 forces the window to empty completely,
and the count still stays within the bound.
Complexity
| Version | Time | Extra space |
|---|---|---|
| Every subarray, summed directly | O(n³) (O(n²) with a running sum per start) | O(1) |
| Fixed window, recomputed | O(n·k) | O(1) |
| Fixed window, sliding | O(n) | O(1) |
| Variable window, expand/shrink | O(n): ≤ 2n updates | O(1) |
| Variable window with a frequency map (e.g. distinct letters) | O(n) expected | O(alphabet) |
Beyond sums
The same skeleton works whenever the summary can be updated incrementally:
- Counts or frequencies: "longest substring without a repeated letter" keeps a map from letter to count and shrinks while some count exceeds 1. See The longest stretch without a repeated letter.
- Fixed window of totals: The busiest stretch of k hours is exactly the fixed-size algorithm above.
- Maximum or minimum of every window: a sum can be updated by subtraction, a maximum cannot (when the maximum leaves, what is the next one?). That needs a monotonic deque, covered with queues and deques.
When the window is not monotonic (adding an element can make a bad window good again), the pattern does not apply. "Number of subarrays with sum exactly k" on arrays with negative values is the classic case; it is solved with prefix sums and a hash map in How many stretches add up to k?.
Language notes
Overflow. A window of 32-bit values can sum past 2³¹ − 1. The listings keep sums in long
(C#, Java) or std::int64_t (C++). There is a second, easy-to-miss trap in the slide step:
values[right] - values[right - k] is computed in int before it is added to the 64-bit sum,
and the difference of two ints can overflow too. The listings widen first:
(long)values[right] - values[right - k]. Python integers have arbitrary precision. If you would
rather detect overflow than avoid it, C# has checked arithmetic and Java has Math.addExact.
Signed indices in C++. The variable version uses std::ptrdiff_t so that best_start can be
−1 and right − left + 1 cannot wrap around when the window is empty (left = right + 1).
Library support.
| Language | Windows built in | Notes |
|---|---|---|
| C# | none for sliding windows (Chunk splits into non-overlapping blocks) |
write the loop |
| Python | itertools docs include a sliding_window recipe built on collections.deque(maxlen=k) |
the recipe yields tuples; summing each is O(k) |
| Java | none | write the loop |
| C++23 | std::views::slide(values, k) |
a view of overlapping subranges; summing each is still O(k) |
The library views give you the windows, not the O(1) update: summing each window they produce is the O(n·k) approach. The incremental update is the point of the technique.
The teaching implementation
MaxSumOfK / max_sum_of_k and LongestWithSumAtMost / longest_with_sum_at_most are written
the same way in all four languages. Each language reads one shared fixture (empty array, one value,
k = n, invalid k, negatives, ties, zeros, a value above the limit, extremes) in which rows with
negative values are marked "n/a" for the variable window: its precondition excludes them. Each
language also compares both functions with a brute-force scan of every window on 1,000 random
arrays, and the C#, Java and C++ tests include sums beyond the 32-bit range.
Common mistakes
- Off-by-one on the leaving index. In a fixed window ending at
right, the value that leaves isvalues[right − k], notvalues[right − k + 1]. - Using the variable window with negative values. It returns a plausible but wrong answer; nothing fails loudly.
ifinstead ofwhilewhen shrinking. One removal may not be enough to make the window valid again.- Recording the answer before shrinking. Only the window after the shrink loop is valid.
- Forgetting invalid
k(0, or larger than the array) in the fixed version.
Edge cases
- Empty array: no fixed window exists (the listings reject it); the longest valid run has length 0.
- Every value above the limit: each one enters and immediately leaves; the answer is length 0.
- Limit 0: only runs of zeros qualify.
k = n: one window, no slides.
Worked practice
1. Largest sum of 2 consecutive values in [3, −1, 4, −1, 5]?
Answer
Windows: 2, 3, 3, 4. The largest is 4, starting at index 3 (−1 + 5).
2. Longest run with sum ≤ 6 in [2, 3, 1, 4, 1, 1]?
Answer
Length 3. [2, 3, 1] (sum 6) is found first at start 0; [4, 1, 1] also has length 3 but does
not beat it, so the result is start 0, length 3.
3. Give an input with a negative value where "shrink while too big" fails.
Answer
Limit 3, values [5, −4, 1]. The correct answer is the whole array (sum 2, length 3); the window
discards 5 immediately and ends with length 2.
4. Why is the shrink loop O(n) in total and not O(n) per step?
Answer
Every iteration of the inner loop moves left forward by one, and left never moves back or past
right + 1. So across the whole run the inner loop executes at most n times in total.
Summary
- A window is a contiguous range plus a summary that can be updated from the entering and leaving values.
- Fixed windows: add one, subtract one; O(n) instead of O(n·k); any integers.
- Variable windows: expand on the right, shrink from the left while invalid; correct when the validity is monotonic, for sums that means non-negative values.
- Each index enters and leaves at most once, so the nested loop is O(n) overall.
- Keep sums in 64 bits in C#, Java and C++, and widen before subtracting.