Static & Dynamic Arrays

Sort Colors

Medium
Solve it on LeetCode ↗

The problem

Sort an array containing only 0s, 1s, and 2s in place, without using the library sort — ideally in a single pass.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Keep three pointers: low (end of the 0-region), mid (current), high (start of the 2-region).
  2. 2nums[mid] === 0 → swap with low, advance both.
  3. 3nums[mid] === 1 → just advance mid.
  4. 4nums[mid] === 2 → swap with high, decrement high, do NOT advance mid (the swapped-in value is unexamined).
  5. 5Stop when mid passes high.

Key insight

After swapping with high you must re-examine position mid — the incoming value is unknown. Swaps with low are safe because everything below mid is already classified.

The solution

Watch out for

  • Advancing mid after a high-swap is THE bug everyone writes first.
  • Loop condition is mid <= high (inclusive) — high itself is unexamined.