Two Pointers Visualization

Find a pair of elements with a specific sum in a sorted array using two converging pointers.

Target Sum:
Ready to start
Ready
Speed

Pseudocode

1function twoSum(arr, target)
2 left = 0, right = n - 1
3 while left < right
4 sum = arr[left] + arr[right]
5 if sum == target
6 return [left, right]
7 if sum < target
8 left++
9 else
10 right--
11 return -1

Time Complexity

Best CaseO(1)
Average CaseO(n)
Worst CaseO(n)

Note:

This technique works because the array is sorted. We can safely conclude that if sum < target, we need a larger value (move left pointer right), and vice versa.