Algorithms · intermediate

Two pointers

The two-pointers technique maintains two positions whose coordinated movement eliminates candidates or summarizes a range without restarting a full scan.

Why it matters

A proven movement rule often turns nested search into a linear pass for sorted pairs, partitioning, deduplication, or linked-list cycle detection.

Mental model

How to reason about two pointers

Each pointer encodes a boundary. After inspecting their current state, move the pointer whose side can be ruled out while preserving the invariant for the remaining region.

Analogy

Two bookends move inward around a sorted shelf; each comparison tells which end cannot participate in the desired pair.

Examples

See the boundary, not just the happy path

Worked example · Pair sum in sorted data

sum < target -> left++; sum > target -> right--

Sorted order proves that moving the opposite pointer would only move the sum farther from the needed direction.

Worked example · Compact unique values

read scans input; write marks the next unique output slot

The pointers separate consumed input from the compacted prefix, enabling in-place linear deduplication.

Useful contrast · Unsorted pair sum

[8, 1, 6, 3], target 9

Without ordering, increasing or decreasing a pointer gives no monotonic information. A hash set is a more suitable linear-time approach.

Common mistakes

Misconceptions to remove early

Moving a pointer without a proof

The technique is not merely 'use two indexes.' Each movement must eliminate candidates without discarding a possible solution.

Reusing the sorted rule on unsorted data

Opposing-pointer sum logic depends on monotonic order. Sort first if that total cost is acceptable, or choose a hash-based method.

Quick check

Can you predict the result?

1. In a sorted pair-sum search, the current sum is too small. Which pointer should move?
  • Move the left pointer right to increase the sum
  • Move the right pointer left to decrease the sum
  • Reset both pointers to the middle
Answer: Move the left pointer right to increase the sum
2. What makes a two-pointer movement rule correct?
Answer: An invariant, often ordering, that proves the candidates skipped by that movement cannot be valid answers.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster