Sort Colors
Difficulty: Medium
You're given an array of only 0s, 1s and 2s (think of them as three colors: red, white and blue). Rearrange it in place so all 0s come first, then all 1s, then all 2s.
Try not to use a general-purpose sort, and ideally use a single pass.
Examples
Input: nums = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Input: nums = [2, 0, 1]
Output: [0, 1, 2]
Input: nums = [0]
Output: [0]
A single element is already sorted; there's nothing to rearrange.
Constraints
1 <= nums.length <= 300
nums[i] is 0, 1, or 2.
Approach
A general-purpose comparison sort works, but it's more than the problem needs and ignores that there are only three possible values.
The optimal approach, the Dutch National Flag algorithm, uses three pointers: the next place for a 0 (growing from the front), the next place for a 2 (growing from the back), and a scanner moving left to right.
- When the scanner sees a 0, swap it toward the front.
- When it sees a 2, swap it toward the back.
- Leave 1s where they are, since they belong in the middle.
This sorts the array in place in a single pass.
Solutions
Brute Force — Built-in Sort
Use a general-purpose comparison sort. Correct and simple, but it ignores that there are only three possible values.
function sortColors(nums) {
nums.sort((a, b) => a - b);
}Time: O(n log n) · Space: O(log n) (typical sort implementation's internal stack space)
Optimal — Dutch National Flag (Three Pointers)
Keep three pointers: low marks the next spot for a 0, high marks the next spot for a 2 (from the back), and mid scans through the array. Swap 0s toward low and 2s toward high; when a 1 is seen, just move past it.
function sortColors(nums) {
let low = 0;
let mid = 0;
let high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
[nums[low], nums[mid]] = [nums[mid], nums[low]];
low++;
mid++;
} else if (nums[mid] === 1) {
mid++;
} else {
[nums[mid], nums[high]] = [nums[high], nums[mid]];
high--;
// mid isn't advanced here — the value swapped in from the back
// still needs to be checked
}
}
}Time: O(n) · Space: O(1)