Converging Pointers
Opposite-ends two pointers
Two pointers start at opposite ends of a sorted array and walk toward each other, using the sort order to safely discard one candidate every step. Reach for it whenever sorted data lets a single comparison tell you which end to shrink.
Details
Animated on: Two Sum II: find two numbers in the sorted array [1, 3, 4, 6, 8, 11] that add up to 10
Problem:Two Sum II - Input Array Is SortedMedium
Pattern:Two Pointers
Opposite-ends two pointers
step 1 / 11
Sorted array, target 10. Put l on the smallest value and r on the largest — the sum can only be steered from these two ends.
- l=0· arr[0] = 1
- r=5· arr[5] = 11
1FUNCTION twoSumSorted(arr, target):2 set l to 0 and r to the last index of arr3 WHILE l < r:4 sum = arr[l] + arr[r]5 IF sum equals target: RETURN [l, r]6 IF sum < target: move l one step right7 ELSE: move r one step left8 END WHILE9 RETURN nothing (no pair found)10END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 11 steps
- Sorted array, target 10. Put l on the smallest value and r on the largest — the sum can only be steered from these two ends.
- sum = arr[l] + arr[r] = 1 + 11 = 12. Compare it against target 10.
- 12 > 10: too big. Even the smallest value 1 overshoots with 11, so 11 can pair with nothing. Discard it — r moves left.
- New pair: sum = 1 + 8 = 9. Compare against 10.
- 9 < 10: too small. 8 is the biggest partner left, so 1 can never reach 10 with anyone. Discard 1 — l moves right.
- sum = 3 + 8 = 11. Compare against 10.
- 11 > 10: overshoot. 8 just failed with the smallest remaining value 3, so any partner for 8 overshoots too. Discard 8 — r moves left.
- sum = 3 + 6 = 9. Compare against 10.
- 9 < 10: too small. 6 is the largest partner left for 3 and it still falls short — 3 is out. l moves right.
- sum = 4 + 6 = 10. Compare against 10.
- 10 === target. Found it: arr[2]=4 + arr[3]=6 = 10. Return [2, 3] — one pass, each element examined at most once.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.