Two pointers
Two pointers is a technique that walks a sequence with a pair of indices instead of nested loops. The pointers move toward each other, or in the same direction, and each item is processed a constant number of times.
Detailed Explanation
A nested loop that asks "for each i, look at every j > i" is O(n²). If the array is sorted, or if the inner scan only needs to move forward, you can often keep a second index that never resets. That is two pointers.
The facing-pair form starts at both ends. On a sorted list, "do two numbers sum to target?" moves the left pointer right when the sum is too small, and the right pointer left when the sum is too large. Each step discards an index forever, so the loop is O(n) after the sort.
The same-direction form is a fast and a slow index, or a read and a write index. Removing zeros in place: the write pointer stays on the next slot to fill, the read pointer scans. Detecting a cycle in a linked list: Floyd's tortoise and hare. Merging two sorted lists: one pointer per list.
The invariant is the part you should write down. "Everything left of i is already correct." "The pair (lo, hi) is the remaining candidate window." If you cannot state the invariant, you cannot tell whether a move is legal.
Two pointers need a sequence you can index, or two iterators you can advance. They do not need extra data structures, which is why the auxiliary space is often O(1). When the problem needs "have I seen this value?", a set is the other O(n) tool; two pointers do not replace hashing on unsorted unique-lookup problems.
Python's i, j = 0, len(a) - 1 and a while i < j is the usual skeleton. Be careful with i += 1 after a swap so you do not process the same pair twice, and with empty inputs so a[0] does not raise.
Code Examples
def two_sum_sorted(nums: list[int], target: int) -> tuple[int, int] | None:
lo, hi = 0, len(nums) - 1
while lo < hi:
total = nums[lo] + nums[hi]
if total == target:
return lo, hi
if total < target:
lo += 1
else:
hi -= 1
return None
print(two_sum_sorted([1, 2, 4, 7, 11], 11)) # (1, 3) -> 2 + 9? wait 2+7=9, 4+7=11 -> (2, 3)def compact_nonzero(nums: list[int]) -> int:
"""Move non-zeros forward. Return the new logical length."""
write = 0
for read, value in enumerate(nums):
if value != 0:
nums[write] = value
write += 1
return write
data = [0, 3, 0, 4]
n = compact_nonzero(data)
print(data[:n]) # [3, 4]Common Gotchas
Using two pointers on an unsorted array for a sum
the facing-pair proof needs order. Sort first, or use a set.
Off-by-one on `lo < hi` vs `lo <= hi`
a middle element handled twice, or never, is the usual bug. Test odd lengths.
Moving both pointers after a hit
you may skip a valid pair. Move one, or record and continue according to the problem.
`enumerate` is one pointer
the second is an integer you update by hand.