Sort Colors
Sort Colors is LeetCode 75 (Medium). The array nums holds only 0, 1 and 2, standing for red, white and blue. Rearrange it in place so all 0s come first, then the 1s, then the 2s.
- The library sort is not allowed.
- Follow-up: do it in one pass with constant extra space.
- n == nums.length
- 1 <= n <= 300
- nums[i] is either 0, 1, or 2.
Intuition
With only three values, sorting is really splitting the array into three blocks. Three pointers cut it into four zones: before low are 0s, from low to mid - 1 are 1s, from mid to high is unchecked, and after high are 2s.
Each step looks at nums[mid] and shrinks the unchecked zone by one:
- A 0: swap it to
low. Both pointers move, because the value coming back fromlowis a 1 that was already checked. - A 1: it already belongs to the middle block, so only
midmoves. - A 2: swap it to
highand movehighin.midstays, because the value coming back has never been checked.
This is known as the Dutch national flag algorithm.
A handful of distinct values to group in place, with one pass required, calls for pointer-marked regions. Partitioning around a pivot in three-way quicksort and Move Zeroes use the same idea with fewer blocks.
Approach
Before reading on, decide what is true about the array to the left of low and to the right of high at every moment. Then work out, for each of the three values at mid, which pointers may move after a swap and which must not.
Two ways to solve it
Grow a 0s block from the left and a 2s block from the right while mid checks each value once.
- One pass: meets the follow-up.
- Watch out:
midmust not move after a swap withhigh.
Count how many 0s, 1s and 2s there are, then overwrite the array with that many of each.
- Simplest: hard to get wrong.
- Two passes: one to count, one to write.
Both run in O(n) time and O(1) space. The three-pointer method wins because it meets the one-pass follow-up and moves the original values instead of rewriting them. The steps, code and live demo follow the three-pointer method, and the counting code comes after the demo.
Start with everything unchecked
Set low = mid = 0 and high = n - 1. The 0s and 1s blocks are empty and the whole array lies between mid and high, so the four-zone picture already holds before the first step.
Loop while the unchecked zone is not empty
Run while mid <= high. The zone runs from mid to high inclusive, so when the two are equal one value is still waiting to be looked at.
Send a 0 to the front
Swap nums[mid] with nums[low], then add 1 to both. While the 1s block is still empty, low equals mid and the swap leaves the array as it is, which is harmless.
Step over a 1
Add 1 to mid. The 1s block ends just before mid, so moving mid past this value is all it takes to include it.
Send a 2 to the back and look again
Swap nums[mid] with nums[high] and subtract 1 from high. Leave mid where it is so the next loop classifies the value that just arrived.
Code in Python, C++ and Java
Counting sort for three values
The first loop fills count[0], count[1] and count[2]. The second walks through the colours in order and writes each one as many times as it was counted. It is a good first answer in an interview before you are asked for one pass.
Common pitfalls
Moving mid after swapping a 2
nums[mid], nums[high] = nums[high], nums[mid] high -= 1 mid += 1
nums[mid], nums[high] = nums[high], nums[mid] high -= 1
On [1, 2, 0] the 2 swaps with the 0, giving [1, 0, 2]. Moving mid now skips that 0, the loop ends, and the result [1, 0, 2] is not sorted.
Stopping when mid reaches high
while mid < high:
while mid <= high:
On [1, 0] the 1 moves mid to index 1, which equals high, so the loop quits before the 0 is ever checked and returns [1, 0].
Edge cases
[2, 2, 2]Every step swaps a 2 with itself at high and moves high left. The loop ends with high = -1 and the array unchanged, which is already sorted.
Complexity
mid right or moves high left, so the unchecked zone shrinks by exactly one each time. That gives at most n loops and one pass. Only three index variables are used.Sort Colors FAQ
Why is it called the Dutch national flag problem?
Edsger Dijkstra posed it with balls in the three colours of the Dutch flag, red, white and blue, which had to end up in flag order. The three values here stand for those three stripes.
Is this sort stable?
No. A 2 swapped to the back can jump over other 2s, so equal values change order. Plain integers cannot tell the difference, but if each colour were attached to a record, the order of records with the same colour would not be kept.