Learn / Arrays

Two pointers

Two indexes that move through the data with a rule, never backwards. From opposite ends of a sorted array they find pairs; side by side they rewrite an array in place; one per array they merge.

How to recognise it

  • The array is sorted (or you can sort it) and you need a pair or triplet with a target sum or difference.
  • You must change the array in place with O(1) extra memory (remove, move, compact values).
  • Two sorted arrays must be combined, intersected or walked together.
  • Something is compared from both ends inwards (palindromes, water between walls).

The idea in one picture

Two people search a sorted row of numbered cards for a pair that adds up to 50. One starts at the smallest card, one at the largest. If their sum is too small, the person on the small side steps right; too big, the person on the large side steps left. Neither ever steps back, so together they cover the row once. That is the whole trick: a rule tells you which pointer to move, and no pointer moves backwards, so the work is O(n) instead of O(n²).

Three shapes

ShapePointersUsed for
Opposite endsleft = 0, right = n - 1, move inwardspair sums on sorted data, palindromes, trapped water
Read and writeboth start at the front; read scans, write marks the next free slotremoving or moving values in place
One per arrayi in the first array, j in the secondmerging, union, intersection of sorted arrays

Template: pair with a target sum in a sorted array

left = 0
right = n - 1
while left < right:
    sum = nums[left] + nums[right]
    if sum == target: found
    else if sum < target: left = left + 1     # need bigger
    else: right = right - 1                   # need smaller

Every pair the loop skips is provably no good: if the sum is too small with the largest remaining partner, nums[left] cannot be in any pair, so it is safe to drop.

From pairs to triplets and quadruplets

Fix one element with a loop and run the pair template on the rest: 3Sum is O(n²). Fix two and run it on the rest: 4Sum is O(n³). To avoid repeated answers, skip any fixed value equal to the one before it, and skip repeats of the pointer values after recording a match.

A guided example: move the zeros of [0, 1, 0, 3, 12] to the end, keeping order

readvalueactionarraywrite
00skip[0, 1, 0, 3, 12]0
11swap into slot 0[1, 0, 0, 3, 12]1
20skip[1, 0, 0, 3, 12]1
33swap into slot 1[1, 3, 0, 0, 12]2
412swap into slot 2[1, 3, 12, 0, 0]3

Common mistakes

  • Using opposite-end pointers on an unsorted array. The "move left to grow the sum" rule needs sorted values.
  • Forgetting to skip duplicates in 3Sum and 4Sum, which reports the same triplet more than once.
  • Overflowing a 32-bit sum in 4Sum, where four values near 10⁹ add up past 2³¹.
  • Merging into the front of an array that still holds values you need.

Problems

0 of 15 solved

Check yourself

In a sorted array, left and right point at values whose sum is too small. Which pointer moves?

Why is 3Sum O(n²) and not O(n³)?

In Move Zeroes, the read pointer scans every element and the write pointer marks where the next non-zero value goes. Why can't write ever pass read?

Merging two sorted arrays into the first one, which has empty space at its end. Why fill from the back?