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 -= 1

What bounds the number of iterations?

Count: iterations.

Measured counts

02000400020004000ncount
Measured
Table
ncount
87
1615
3231
6463
128127
256255
512511
10241,023
20482,047
40964,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)
  1. Each iteration moves exactly one pointer one step inward.
  2. The gap j − i starts at n − 1 and shrinks by 1 per iteration.
  3. 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.