Two Pointers (Pair Sum) visualization

In a sorted array, move a left and right pointer inward to find two values summing to a target.

If A[lo] + A[hi] is too small, only moving lo right can increase it; if too large, only moving hi left can decrease it. Each step discards one candidate, so it is O(n).

Edge cases: the pointers must be different indices (an element cannot pair with itself); duplicates like [3, 3] with target 6 are a valid pair; fewer than two elements means no pair.

Complexity

Time: best O(1), average O(n), worst O(n). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure pairSum(A, target):     // A sorted
  lo ← 0; hi ← n − 1
  while lo < hi:
    s ← A[lo] + A[hi]
    if s = target: return (lo, hi)
    if s < target: lo ← lo + 1
    else: hi ← hi − 1
  return none

More techniques algorithms