0

Two Pointers

Easy

On a sorted array, one pointer at each end. Move the pointer that can only push the sum in the direction you need.

sorted arraylinear
TimeO(n)
SpaceO(1)
Inputsorted numbers | target sum
2
0
3
1
5
2
8
3
11
4
15
5
target16

Find two values summing to 16.

steps0
1 / 9
l = 0; r = n - 1
while l < r:
sum = a[l] + a[r]
if sum == target: return [l, r]
if sum < target: l++
else: r--
Why it matters

Each pointer only moves inward, so together they take at most n steps.

Keyboard
space play← → stepr restartctrl K search
Next visualiser
Sliding Window