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 += 1The 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
Table
| n | count |
|---|---|
| 8 | 15 |
| 16 | 31 |
| 32 | 63 |
| 64 | 127 |
| 128 | 255 |
| 256 | 511 |
| 512 | 1,023 |
| 1024 | 2,047 |
| 2048 | 4,095 |
| 4096 | 8,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
- left only increases and never passes right, so remove runs at most n times in total, across all iterations.
- add runs exactly n times.
- 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.