Sort Colors

medium

You're given an array nums of n items, each painted red, white, or blue — encoded as 0, 1, and 2. Rearrange them in-place so all the reds come first, then the whites, then the blues.

In other words: sort an array that contains only the values 0, 1, and 2, so the result is non-decreasing. The catch — you may not call the language's built-in sort. The array must be reordered inside itself, and the same array is returned.

The real challenge is the follow-up: can you do it in one pass using only constant extra space?

Hints

There are only three distinct values — do you actually need a general-purpose sort?
If you counted how many 0s, 1s, and 2s there are, could you rebuild the array directly?
For one pass: keep three pointers that partition the array into 'known 0s', 'known 2s', and 'still unknown', and sweep the middle once.

Common doubts

No — the problem explicitly forbids the library sort. The point is to exploit that there are only 3 values and beat the general O(n log n) bound.
Sort it in place; the same array is returned so the judge can read the result. Both approaches here modify nums directly.
The value pulled in from the high end hasn't been examined yet, so mid must re-inspect it. On a 0, the incoming value came from below mid and is already sorted, so mid can advance.

Interview follow-ups

Counting sort generalizes cleanly to k buckets in O(n + k). The Dutch-flag three-pointer trick is specific to three partitions; for many values you'd fall back to counting sort or a comparison sort.
Counting sort can be made stable by placing elements using prefix-sum offsets, but for plain 0/1/2 values stability is moot since equal values are indistinguishable.

Fun facts

  • The one-pass algorithm is Edsger Dijkstra's 'Dutch National Flag' problem — named after the red-white-blue Dutch flag.
  • The same three-way partition powers 3-way quicksort, which stays fast even when the input has many duplicate keys.

Asked at

AmazonMicrosoftGoogleFacebookAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Two reds, two whites, two blues — grouped in color order.
Example 2
Input: nums = [2,0,1]
Output: [0,1,2]
One of each, laid out red → white → blue.
Constraints

- n == nums.length - 1 <= n <= 300 - nums[i] is either 0, 1, or 2

Solve this problem →