Tech_Interview_Prep

Two Pointers

Two indices moving through a sequence — from opposite ends or in lockstep — to cut brute-force O(n²) scans to O(n).

Study first: Arrays & Hashing

What it is

Two pointers is a technique for scanning a sequence (usually sorted, or with a monotonic property) using two indices that move according to a rule, instead of nested loops.

Common shapes

  • Opposite ends closing in — e.g. finding a pair that sums to a target in a sorted array: move the low pointer up or the high pointer down based on the comparison.
  • Fast/slow pointers — one pointer advances twice as fast as the other; used for cycle detection and finding the middle element.
  • Read/write pointers — one pointer scans, the other marks where the next valid element should be written, useful for in-place array modification (removing duplicates, partitioning).

Why it beats brute force

A nested loop comparing every pair is O(n²). Two pointers exploit a monotonic property (sortedness, or "moving one pointer can only help, never hurt") to guarantee each pointer moves at most n times, giving O(n).

Prerequisite for

Binary search (pointers bounding a search space), sliding window (a variable-size two-pointer window), and the linked list fast/slow pattern all specialize this idea.