Sort Colors (LeetCode 75): Solution and Explanation

Medium
Array
Two Pointers
Sorting

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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)

  1. Set low = 0, mid = 0 and high = len(nums) - 1.
  2. Loop while mid <= high, which means the unknown region is not empty.
  3. If nums[mid] is 0, swap it with nums[low] and increment both low and mid.
  4. If nums[mid] is 1, increment mid only.
  5. If nums[mid] is 2, swap it with nums[high] and decrement high, leaving mid in place so the swapped-in value is checked next.
  6. When mid passes high, every element has been classified and the array is sorted.

Step-by-step example

nums = [2,0,2,1,1,0]
  1. Start with low = 0, mid = 0, high = 5. nums[0] is 2, so swap with index 5, giving [0,0,2,1,1,2], and high becomes 4.
  2. nums[0] is now 0. Swapping it with itself leaves the array unchanged, and low and mid both become 1.
  3. nums[1] is 0, so the same thing happens and low and mid become 2.
  4. nums[2] is 2, so swap with index 4, giving [0,0,1,1,2,2], and high becomes 3.
  5. nums[2] and nums[3] are both 1, so mid advances to 4, which passes high = 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 -= 1

Time and space complexity

Time

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.

Space

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 mid after swapping with high. The value that arrives from the back is unexamined and might be a 0 or another 2.
  • Using mid < high as the loop condition, which leaves the element at high unchecked when the pointers meet.
  • Not advancing mid after swapping with low. The value that comes back from low is already classified, and holding mid still lets it fall behind low, so later swaps push values into the wrong region.
  • Calling sorted or nums.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.