AlgoViz

Two pointers (pattern)

easy 14 min

Two pointers walks one list with two indexes instead of one.

Where it shows up

The same pattern appears across everyday software.

  • Merging sorted data

    Merge sort, database merge joins and log-file merges walk two sorted inputs with one index each.

  • In-place cleanup

    Filtering a large buffer without allocating a copy, for example dropping deleted records before a write, uses a reader and a writer index.

  • Diff and sync tools

    Comparing two sorted lists of file names or ids to find what was added or removed is a two-index walk.

  • Cycle detection

    Slow and fast pointers find loops in linked structures and in repeated state sequences with constant memory.