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
- 1Keep three pointers: low (end of the 0-region), mid (current), high (start of the 2-region).
- 2nums[mid] === 0 → swap with low, advance both.
- 3nums[mid] === 1 → just advance mid.
- 4nums[mid] === 2 → swap with high, decrement high, do NOT advance mid (the swapped-in value is unexamined).
- 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.