Skip to main content
CSAlgorithms & ComplexityDiagramBeginner

Two Pointers

KO: 투 포인터·EN: Two Pointers·JA: ツーポインタ(尺取り法)

A linear-time pattern using two moving indices over an array or list to collapse nested O(N²) loops into O(N) with O(1) extra space

Table of Contents

Structure Diagram

Two Pointers Converging O(N) ScanTap a node
If < targeIf > targemovemoveLeft [0] …[1] 5L + R = 1…[2] 7Right [3]…
ROOTLeft [0] → 2
2 links
Quick Answer

What is Two Pointers?

A linear-time pattern using two moving indices over an array or list to collapse nested O(N²) loops into O(N) with O(1) extra space. It is a core concept in Algorithms & Complexity within CS.

Core Principles

The Two Pointers technique maintains two indices over a linear structure that advance monotonically, turning brute-force O(N²) nested loops into O(N) time and O(1) extra space.

  • Converging Pointers: Start at both ends of a sorted array; increment left when the sum is too small or decrement right when too large.
  • Fast & Slow Pointers: Move in the same direction at different speeds for cycle detection or in-place array compaction.

Practical Takeaways

  • Verify monotonicity: Opposite-end pointers require sorted data so each move provably eliminates invalid candidates.
  • Zero-allocation in-place edits: Pairing a read and write pointer filters or deduplicates arrays in place without allocating temporary buffers.
  • Mind termination boundaries: Clearly distinguish left < right from left <= right to avoid skipping or double-counting the middle item.

Notable Examples

  • Database Sort-Merge Join: Joining two sorted tables in a single O(N + M) linear pass.
  • Floyd's Tortoise & Hare: Detecting linked-list cycles in O(1) memory.
  • Merge Sort Combine Step: Merging two sorted halves linearly.