Skip to content
Commitwise
Menu

Two pointers

A technique that walks an array or string with two indices, moving toward each other or in the same direction, to avoid nested loops.

Definition

Instead of checking every pair of elements, two indices move through the data once. From both ends, they solve palindrome checks and pair-sum problems on sorted arrays. In the same direction, one reads and one writes, which removes or compacts elements in place. Each move must rule out candidates that can't be the answer, which usually requires sorted input.

In practice

To find two numbers in a sorted array that add up to a target, start at both ends: move the left pointer right when the sum is too small and the right pointer left when it is too big.

Learn it in context

Lessons that use this term.

Related terms

Esc

Type to search the whole site.