The problem. An array nums holds only the values 0, 1 and 2 — think of them as red, white and blue. Sort it in place so all 0s come first, then all 1s, then all 2s. You may not use a library sort, and the follow-up asks for a single pass.
Input: nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Input: nums = [2, 0, 1]
Output: [0, 1, 2]This is a sort with a twist: there are only three possible values. The puzzle is famous as the Dutch national flag problem (the Dutch flag is three stripes), posed by Edsger Dijkstra.
Ignore the hint and call a general-purpose sort. It works for any values, so it certainly works for 0, 1 and 2.
function sortColors(nums) { nums.sort((a, b) => a - b);}Time O(n log n), space up to O(n) depending on the language's sort. Correct, but it throws away the most useful fact we have: there are only three possible values. (Most interviewers also forbid the library sort here.)
Count how many 0s, 1s and 2s there are, then write that many of each back into the array, in order.
function sortColors(nums) { const count = [0, 0, 0]; for (const x of nums) count[x]++; let i = 0; for (let value = 0; value <= 2; value++) { for (let c = 0; c < count[value]; c++) nums[i++] = value; }}Time O(n), space O(1) — already linear. But it walks the array twice, and the classic follow-up asks: can we sort it while reading each element only once?
Keep the array split into four zones as you go. The 0s live at the front, the 2s at the back, the 1s in the middle — and one zone is still unknown. Three pointers mark the borders:
mid looks at the first unknown value, and there are only three things it can be:
The subtle rule is the last one. When we swap a 2 to the back, the value that comes from high hasn't been looked at yet — so mid must not move. When we swap a 0 to the front, the value coming from low is a 1 we've already checked (or it's the same element), so mid can safely move on.
We stop when mid passes high: the unknown zone is empty.
Watch the three pointers squeeze the unknown zone from both ends. The tinted cells at each end are finished.
Time O(n), space O(1), in a single pass. Every step either moves mid forward or high backward, so the loop runs at most n times.
O(n log n)A general sort ignores that there are only three values.
O(n)Up to O(n), depending on the language's sort.
O(n)Counting and the Dutch flag are both linear — written O(2n) and O(n) above to show the counting version reads the array twice, while the flag needs only one pass.
[0, 1, 2].[2, 2, 1, 0, 0].[1, 1, 1] or [2, 2].[2, 0, 2, 0].This three-way partition is exactly what makes quicksort fast on arrays with many repeated values ("3-way quicksort"). The same zone-and-pointer thinking also splits an array into negatives and positives, or evens and odds, in one pass.
Two passes: count the 0s, 1s and 2s, then rewrite the array.
O(1)Just three counters.
O(n)Each step moves mid forward or high back, so at most n steps in one pass.
O(1)Only three pointers.