Sort Colors
Problem
An array nums contains only the values 0, 1, and 2, representing three colors. Rearrange the array in place so that all 0s come first, then all 1s, then all 2s, without calling a library sort. The target is a single pass over the array using constant extra memory.
numshas between 1 and 500 elements.- Every element is
0,1, or2; any of the three may be absent entirely.
Examples
nums = [1, 2, 0, 0, 2, 1, 2]→[0, 0, 1, 1, 2, 2, 2].nums = [2, 1, 0]→[0, 1, 2]. One of each, in reverse order.nums = [2, 2, 2, 2, 1, 1]→[1, 1, 2, 2, 2, 2]. No zeros at all; the algorithm must not depend on every color being present.
Hints
- With only three values, you could count them and overwrite the array. Why might the interviewer reject that, and what constraint is it violating?
- Partitioning around a pivot moves elements to one of two sides. Can you maintain three regions at once?
- Dutch national flag: pointers
low,mid,high; everything beforelowis 0, everything afterhighis 2,midscans the unknown middle.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.