Exercise 28 of 30 · advanced · sliding window · amortized · linear

A while loop inside a for loop (sliding window)

The code

left = 0
for right in range(n):
    add(a[right])
    while window_invalid():
        remove(a[left])
        left += 1

The inner loop can run up to n times. Is the total Θ(n²)?

Count: add + remove calls (worst case: the window shrinks to 1 every time).

Measured counts

0500020004000ncount
Measured
Table
ncount
815
1631
3263
64127
128255
256511
5121,023
10242,047
20484,095
40968,191

Try to name the class from the shape before opening the answer.

Show the answer and derivation
Time
Θ(n) (amortized O(1) per step)
Extra space
O(window)
Exact count
≤ 2n
  1. left only increases and never passes right, so remove runs at most n times in total, across all iterations.
  2. add runs exactly n times.
  3. Total ≤ 2n: Θ(n). The inner loop is expensive sometimes but cheap on average.

Common mistake: Multiplying the maximum inner count by the outer count. Bound the total movement of `left` instead.

Check: measured count ÷ (n) settles near 2.00 for large n.