Courses / DSA Patterns for Working Engineers / Chapter 2
Module 2 · Pointers, windows, intervals and linked lists · Chapter 2 of 39
Two Pointers: Pairs, Partitions and In-Place Scans
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Fast and Slow Pointers: Cycles, Midpoints and Repeats.
Part 1 · Introduction to two pointers
Two indices instead of one
Many array problems look like they need a loop inside a loop: compare every item with every other item. Two pointers replaces that with a single pass in which two indices move, and it applies whenever the data has enough structure to tell you which index to move.
A pointer here is just an integer index into an array or string. A two pointers algorithm keeps two of them, moves them according to a rule, and stops when they meet or run off the end. Each step moves at least one pointer and no pointer moves back, so the total number of steps is at most the length of the input, written O(n) (read "order n"). The nested version does about n squared steps.
There are three common shapes, and the rest of this chapter uses each one.
| Shape | Start | Move | Typical use |
|---|---|---|---|
| Opposite ends | One at each end of a sorted array or a string | Inward, one at a time, by a comparison |