The two-pointer technique uses two indices that move through a sequence to solve problems in a single pass — turning many O(n²) brute-force solutions into O(n).
The idea
Keep two pointers (often at the ends, or one slow and one fast) and move them based on a condition, shrinking the work without rescanning.
Example: pair summing to a target in a sorted array
():
lo, hi = , (arr) -
lo < hi:
s = arr[lo] + arr[hi]
s == target:
(lo, hi)
s < target:
lo +=
:
hi -=
two_sum_sorted([, , , , ], )
