Sort Colors (LeetCode 75): Solution and Explanation
You have an array containing only the values 0, 1 and 2, standing for three colors. Sort it in place so that all 0s come first, then all 1s, then all 2s, without using a library sort.
Watch it run step by step
Try your own input and write the code →Intuition
The easiest correct solution is counting sort. Count how many 0s, 1s and 2s there are, then overwrite the array with that many of each. It is O(n) and simple, but it takes two passes, and the follow-up asks for a single pass using constant extra space.
To do it in one pass, think about what the array looks like midway through. You want a region of 0s at the front, a region of 2s at the back, 1s in between, and an unexplored region still to classify. Three pointers describe that layout: everything before low is 0, everything from low up to mid is 1, everything after high is 2, and the part from mid to high is unknown. This is the Dutch national flag partition.
Each step looks at nums[mid] and shrinks the unknown region by one. A 0 belongs at the front, so swap it with nums[low] and advance both low and mid; what comes back from low is already known to be a 1, so it is safe to move past. A 1 is already where it belongs, so just advance mid. A 2 belongs at the back, so swap it with nums[high] and shrink high, but do not advance mid, because the value that came from the back has not been examined yet.
Approach: Dutch national flag (three pointers)
- Set
low = 0,mid = 0andhigh = len(nums) - 1. - Loop while
mid <= high, which means the unknown region is not empty. - If
nums[mid]is 0, swap it withnums[low]and increment bothlowandmid. - If
nums[mid]is 1, incrementmidonly. - If
nums[mid]is 2, swap it withnums[high]and decrementhigh, leavingmidin place so the swapped-in value is checked next. - When
midpasseshigh, every element has been classified and the array is sorted.
Step-by-step example
nums = [2,0,2,1,1,0]
- Start with
low = 0,mid = 0,high = 5.nums[0]is 2, so swap with index 5, giving [0,0,2,1,1,2], andhighbecomes 4. nums[0]is now 0. Swapping it with itself leaves the array unchanged, andlowandmidboth become 1.nums[1]is 0, so the same thing happens andlowandmidbecome 2.nums[2]is 2, so swap with index 4, giving [0,0,1,1,2,2], andhighbecomes 3.nums[2]andnums[3]are both 1, somidadvances to 4, which passeshigh = 3. The result is [0,0,1,1,2,2].
Code: Python, Java, C++
1class Solution:
2 def sortColors(self, nums: List[int]) -> None:
3 low, mid, high = 0, 0, len(nums) - 1
4
5 while mid <= high:
6 if nums[mid] == 0:
7 nums[low], nums[mid] = nums[mid], nums[low]
8 low += 1
9 mid += 1
10 elif nums[mid] == 1:
11 mid += 1
12 else: # nums[mid] == 2
13 nums[mid], nums[high] = nums[high], nums[mid]
14 high -= 11class Solution {
2 public void sortColors(int[] nums) {
3 int low = 0, mid = 0, high = nums.length - 1;
4
5 while (mid <= high) {
6 if (nums[mid] == 0) {
7 int temp = nums[low];
8 nums[low] = nums[mid];
9 nums[mid] = temp;
10 low++;
11 mid++;
12 } else if (nums[mid] == 1) {
13 mid++;
14 } else {
15 int temp = nums[mid];
16 nums[mid] = nums[high];
17 nums[high] = temp;
18 high--;
19 }
20 }
21 }
22}1class Solution {
2public:
3 void sortColors(vector<int>& nums) {
4 int low = 0, mid = 0, high = nums.size() - 1;
5
6 while (mid <= high) {
7 if (nums[mid] == 0) {
8 swap(nums[low], nums[mid]);
9 low++;
10 mid++;
11 } else if (nums[mid] == 1) {
12 mid++;
13 } else {
14 swap(nums[mid], nums[high]);
15 high--;
16 }
17 }
18 }
19};Time and space complexity
O(n)
Every iteration either advances mid or decrements high, so the unknown region shrinks by one each time and the loop runs at most n times.
O(1)
The sort uses three index variables and swaps in place.
Other approaches
Counting sort (time O(n), space O(1))
Count the 0s, 1s and 2s in one pass, then rewrite the array in a second pass. It is the simplest linear solution and is perfectly acceptable unless one pass is required.
Two-pass partition (time O(n), space O(1))
First move all 0s to the front with a write pointer, then move all 1s right after them in a second pass. It is easier to get right than three pointers but reads the array twice.
Common mistakes
- Advancing
midafter swapping withhigh. The value that arrives from the back is unexamined and might be a 0 or another 2. - Using
mid < highas the loop condition, which leaves the element athighunchecked when the pointers meet. - Not advancing
midafter swapping withlow. The value that comes back fromlowis already classified, and holdingmidstill lets it fall behindlow, so later swaps push values into the wrong region. - Calling
sortedornums.sort(). It produces the right output but defeats the purpose of the problem and costs O(n log n).
Frequently asked questions
What is the Dutch national flag problem?
It is the task of partitioning an array into three groups around a pivot value, named after the three horizontal bands of the Dutch flag. The three-pointer solution is the classic one-pass answer and is also used inside three-way quicksort.
Why don't we increment mid after swapping with high?
The element swapped in from high comes from the unexplored region, so its color is unknown. Leaving mid in place makes the next iteration examine it before moving on.
Is Sort Colors stable?
No. Swapping moves equal values past each other, so the relative order of equal elements is not preserved. That does not matter here because equal values are indistinguishable.
Can Sort Colors be solved in one pass?
Yes. The three-pointer partition classifies each element in a single sweep and uses constant extra space, which is the standard follow-up requirement.