← Questions
Sort colors (three-way partition in place)
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's technical phone screen, last asked Apr 2026. It tests arrays, two pointers and sorting.
An array items holds only the values 0, 1 and 2, each standing for a category. Rearrange it in place so all 0s come first, then all 1s, then all 2s, in one pass and O(1) extra space, without counting and rewriting.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
sort_colors(items: list[int]) -> None— modifiesitemsin place.
Example
items = [2, 0, 2, 1, 1, 0]
sort_colors(items) # items == [0, 0, 1, 1, 2, 2]
items = [2, 0, 1]
sort_colors(items) # items == [0, 1, 2]
items = [0]
sort_colors(items) # items == [0]
Constraints
-
0 <= len(items) <= 10^5; every element is 0, 1 or 2. - One pass, O(1) extra space.
Clarifying questions
- Is a two-pass counting sort acceptable? (Not here.)
- Do elements carry other data, so the order within a category matters?
- Can the array be empty?
What a strong answer covers
- The Dutch national flag partition with three pointers
low,mid,high, and its invariant:[0, low)are 0s,[low, mid)are 1s,(high, end]are 2s,[mid, high]unknown. - The step rules: a 0 swaps to
lowand both advance; a 1 advancesmid; a 2 swaps tohighand onlyhighmoves, because the swapped-in value is unchecked. - O(n) time, O(1) space; the loop ends when
mid > high. - Why it is not stable, and when that matters.
- Tests: empty, all one value, already sorted, reverse sorted.
Follow-ups
- Sort an array with k distinct categories in place.
- Partition around a pivot value (
< p,= p,> p) as in quicksort's three-way partition. - Keep the relative order within each category (stable) with O(1) extra space: what does it cost?
Where it's asked
- Microsoft · Technical phone screen · Last asked Apr 202660 min · One technical round
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
