Visualize

Pattern visualizer

Converging 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. Animated on: Two Sum II: find two numbers in the sorted array [1, 3, 4, 6, 8, 11] that add up to 10.

Opposite-ends two pointers

time O(n)space O(1)step 1 / 11
1
[0]
3
[1]
4
[2]
6
[3]
8
[4]
11
[5]
line 2

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.

Pseudocode
1FUNCTION twoSumSorted(arr, target):
2 set l to 0 and r to the last index of arr
3 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 right
7 ELSE: move r one step left
8 END WHILE
9 RETURN nothing (no pair found)
10END FUNCTION

← / → step · space play · Home restart

Where to practice Two Pointers