Exercise 27 of 30 · intermediate · two pointers · linear · potential argument
Two pointers moving toward each other
The code
i, j = 0, len(a) - 1
while i < j:
if a[i] + a[j] < target: i += 1
else: j -= 1What bounds the number of iterations?
Count: iterations.
Measured counts
Table
| n | count |
|---|---|
| 8 | 7 |
| 16 | 15 |
| 32 | 31 |
| 64 | 63 |
| 128 | 127 |
| 256 | 255 |
| 512 | 511 |
| 1024 | 1,023 |
| 2048 | 2,047 |
| 4096 | 4,095 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n)
- Extra space
- O(1)
- Exact count
- n − 1 (when no pair stops it early)
- Each iteration moves exactly one pointer one step inward.
- The gap j − i starts at n − 1 and shrinks by 1 per iteration.
- At most n − 1 iterations: Θ(n).
Common mistake: Seeing two indices and answering Θ(n²). They never restart.
Check: measured count ÷ (n) settles near 1.00 for large n.