Practice Discrete Math

Algorithms / Two Pointers Compaction

Least You Need to Know: Read/Write Pointers, Compaction, and Deduping

A read pointer examines every element while a write pointer marks where the next kept element belongs. This is the core interview pattern for in-place filtering, removing duplicates, and compacting arrays without extra output storage.

The least you need to know

Key notation

read pointer scanning the full input
write index of the next kept output slot
kept prefix prefix `[0, write)` already rewritten correctly

Tiny worked example

  • Scan the array with `read`.
  • When an element should be kept, copy it to `a[write]` and advance `write`.
  • Ignore rejected elements by advancing only `read`.
  • At the end, the valid answer is the prefix of length `write`.

Common mistakes

How to recognize this kind of problem

Start practice