Sort Colors
Pattern: Dutch national flag
Three pointers split the array into 0s, 1s, unknown and 2s. mid looks at each unknown value once, sending 0s to low and 2s to high with a swap.
The problem
You are given an array whose values are only 0, 1 and 2 (three colours). Rearrange it in place so all 0s come first,
then all 1s, then all 2s, without using a library sort. For example, [2, 0, 2, 1, 1, 0] becomes [0, 0, 1, 1, 2, 2].
The function name sortColors matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Counting the 0s, 1s and 2s and rewriting the array works. Can you do it in a single pass?
- If the front of the array is all 0s and the back is all 2s, where should a newly seen 0 go? A 2?
- After swapping a value in from the back, do you know what it is?
Hints
Brute force, and why it fails
A library sort is O(n log n). Counting the three values and rewriting is O(n) but takes two passes. The three-pointer method is one pass with O(1) memory.
The key insight
Each value has only three possible places, and the three regions can grow from known ends. Every step either fixes one value for good or shrinks the unknown region, so one pass is enough.
Dry run
nums = [2, 0, 2, 1, 1, 0]. low = mid = 0 and high = 5. Everything from mid to high is unknown.
The plan
low = 0, mid = 0, high = n - 1
while mid <= high:
if nums[mid] == 0:
swap nums[low], nums[mid]; low = low + 1; mid = mid + 1
else if nums[mid] == 1:
mid = mid + 1
else:
swap nums[mid], nums[high]; high = high - 1
Complexity
- Time
O(n)- Space
O(1)
Each step either moves mid forwards or high backwards, so there are at most n steps.
Edge cases
- One element: nothing to do.
- All the same colour: no real changes.
- Already sorted or reversed, as in
[2, 1, 0]: still one pass.
I've built my logic, show the code
Java
class Solution {
public void sortColors(int[] nums) {
int low = 0; // nums[0..low-1] are all 0
int mid = 0; // nums[low..mid-1] are all 1
int high = nums.length - 1; // nums[high+1..] are all 2; nums[mid..high] is unknown
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums, low++, mid++);
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums, mid, high--); // do not move mid: the value swapped in is still unknown
}
}
}
private void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}C++
class Solution {
public:
void sortColors(vector<int>& nums) {
int low = 0; // nums[0..low-1] are all 0
int mid = 0; // nums[low..mid-1] are all 1
int high = static_cast<int>(nums.size()) - 1; // nums[high+1..] are all 2; nums[mid..high] is unknown
while (mid <= high) {
if (nums[mid] == 0) {
swap(nums[low++], nums[mid++]);
} else if (nums[mid] == 1) {
mid++;
} else {
swap(nums[mid], nums[high--]); // do not move mid: the value swapped in is still unknown
}
}
}
};Python
class Solution:
def sortColors(self, nums: list[int]) -> None:
low = mid = 0 # nums[:low] are 0, nums[low:mid] are 1
high = len(nums) - 1 # nums[high+1:] are 2; nums[mid:high+1] is unknown
while mid <= high:
if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1 # do not move mid: the value swapped in is still unknownCommon mistakes
- Moving
midafter swapping withhigh, which can leave a 0 or 2 in the middle. - Using
mid < highas the loop condition, which skips the last unknown value. - Swapping a 0 with
highor a 2 withlowby mixing up the two ends.