Sort Colors
Medium
Topics
Given an array nums with n objects colored red, white, or blue (0, 1, 2), sort them in-place so objects of the same color are adjacent, in the order 0, 1, 2. Return the sorted array. Use the one-pass Dutch National Flag algorithm.
Example 1
Input: nums = [2,0,2,1,1,0] Output: [0,0,1,1,2,2]
Example 2
Input: nums = [2,0,1] Output: [0,1,2]
Constraints
- n == nums.length
- 1 <= n <= 300
- nums[i] is 0, 1, or 2.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Three distinct values and one pass is the Dutch national flag partition. Maintain three regions with two boundaries: everything below lo is a 0, everything above hi is a 2, and the span between lo and mid is all 1s. The unexamined region is between mid and hi.
The asymmetry is the whole trick. A 0 is swapped in from a region already known to hold 1s, so the incoming value is a 1 and mid can advance safely. A 2 is swapped in from the unexamined region, so the incoming value is unknown and mid must stay put to inspect it.
Approach
- Set
lo = mid = 0andhi = len(nums) - 1. - While
mid <= hi, look atnums[mid]. - On 0, swap with
loand advance bothloandmid. - On 1, advance
midonly. - On 2, swap with
hi, decrementhi, and leavemidalone.
Dry Run
nums = [2,0,2,1,1,0]
lo mid hi array after action
0 0 5 [2,0,2,1,1,0] start
0 0 4 [0,0,2,1,1,2] 2 -> swap to the high end, mid does NOT advance
1 1 4 [0,0,2,1,1,2] 0 -> swap to the low end, both advance
2 2 4 [0,0,2,1,1,2] 0 -> swap to the low end, both advance
2 2 3 [0,0,1,1,2,2] 2 -> swap to the high end, mid does NOT advance
2 3 3 [0,0,1,1,2,2] 1 -> in place, advance mid
2 4 3 [0,0,1,1,2,2] 1 -> in place, mid passes hi, loop ends
answer [0,0,1,1,2,2]Complexity
- Time — O(n): every iteration either advances
midor decreaseshi, and they meet after at most n steps. Strictly one pass. - Space — O(1): three indices, swapping in place.
Common Pitfalls
- Advancing
midafter swapping a 2. The value swapped in came from the unexamined region and has not been looked at; advancing skips it, and a 0 landing there is lost. - Using
mid < hiinstead ofmid <= hi, which leaves the final unexamined cell unsorted. - Counting the three values and overwriting the array. That is the two-pass counting sort, it is correct and O(n), but the problem asks for one pass.
- Calling a library sort. It is O(n log n) on an input whose bounded alphabet admits O(n), and it sidesteps the thing being tested.
- Swapping with
lowhenlo == midand treating it as a bug. It is a self-swap, harmless, and avoiding it with a branch costs more than it saves. - Generalising to k colours with the same two pointers. Dutch flag handles exactly three regions; more colours need counting sort or a different partition scheme.
Full Solution — all languages
class Solution:
def sortColors(self, nums):
lo, mid, hi = 0, 0, len(nums) - 1
while mid <= hi:
if nums[mid] == 0:
nums[lo], nums[mid] = nums[mid], nums[lo]
lo += 1; mid += 1
elif nums[mid] == 1:
mid += 1
else:
nums[mid], nums[hi] = nums[hi], nums[mid]
hi -= 1
return numsimport java.util.*;
class Solution {
public int[] sortColors(int[] nums) {
int lo = 0, mid = 0, hi = nums.length - 1;
while (mid <= hi) {
if (nums[mid] == 0) {
int t = nums[lo];
nums[lo] = nums[mid];
nums[mid] = t;
lo++;
mid++;
} else if (nums[mid] == 1) mid++;
else {
int t = nums[mid];
nums[mid] = nums[hi];
nums[hi] = t;
hi--;
}
}
return nums;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> sortColors(vector<int>& nums) {
int lo = 0, mid = 0, hi = (int)nums.size() - 1;
while (mid <= hi) {
if (nums[mid] == 0) {
swap(nums[lo], nums[mid]);
lo++;
mid++;
} else if (nums[mid] == 1) mid++;
else {
swap(nums[mid], nums[hi]);
hi--;
}
}
return nums;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var sortColors = function(nums) {
let lo = 0, mid = 0, hi = nums.length - 1;
while (mid <= hi) {
if (nums[mid] === 0) {
const t = nums[lo];
nums[lo] = nums[mid];
nums[mid] = t;
lo++;
mid++;
} else if (nums[mid] === 1) mid++;
else {
const t = nums[mid];
nums[mid] = nums[hi];
nums[hi] = t;
hi--;
}
}
return nums;
};