LeetCode #75 Medium

Sort Colors

Sort Colors is LeetCode 75 (Medium). The array nums holds only 0, 1 and 2, standing for red, white and blue. Rearrange it in place so all 0s come first, then the 1s, then the 2s.

  • The library sort is not allowed.
  • Follow-up: do it in one pass with constant extra space.
Constraints
  • n == nums.length
  • 1 <= n <= 300
  • nums[i] is either 0, 1, or 2.
arraytwo-pointersdutch-flag
Open on LeetCode ↗
02

Intuition

With only three values, sorting is really splitting the array into three blocks. Three pointers cut it into four zones: before low are 0s, from low to mid - 1 are 1s, from mid to high is unchecked, and after high are 2s.

Each step looks at nums[mid] and shrinks the unchecked zone by one:

  • A 0: swap it to low. Both pointers move, because the value coming back from low is a 1 that was already checked.
  • A 1: it already belongs to the middle block, so only mid moves.
  • A 2: swap it to high and move high in. mid stays, because the value coming back has never been checked.

This is known as the Dutch national flag algorithm.

How to spot this pattern

A handful of distinct values to group in place, with one pass required, calls for pointer-marked regions. Partitioning around a pivot in three-way quicksort and Move Zeroes use the same idea with fewer blocks.

03

Approach

Try it first

Before reading on, decide what is true about the array to the left of low and to the right of high at every moment. Then work out, for each of the three values at mid, which pointers may move after a swap and which must not.

1

Start with everything unchecked

Set low = mid = 0 and high = n - 1. The 0s and 1s blocks are empty and the whole array lies between mid and high, so the four-zone picture already holds before the first step.

2

Loop while the unchecked zone is not empty

Run while mid <= high. The zone runs from mid to high inclusive, so when the two are equal one value is still waiting to be looked at.

3

Send a 0 to the front

Swap nums[mid] with nums[low], then add 1 to both. While the 1s block is still empty, low equals mid and the swap leaves the array as it is, which is harmless.

4

Step over a 1

Add 1 to mid. The 1s block ends just before mid, so moving mid past this value is all it takes to include it.

5

Send a 2 to the back and look again

Swap nums[mid] with nums[high] and subtract 1 from high. Leave mid where it is so the next loop classifies the value that just arrived.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def sortColors(self, nums):
▶3 low, mid, high = 0, 0, len(nums) - 1
▶4 while mid <= high:
▶5 if nums[mid] == 0:
▶6 nums[low], nums[mid] = nums[mid], nums[low]
▶7 low += 1
▶8 mid += 1
▶9 elif nums[mid] == 1:
▶10 mid += 1
▶11 else:
▶12 nums[mid], nums[high] = nums[high], nums[mid]
▶13 high -= 1
lowmidhigh202110uncheckedeverything is unchecked to start
nums[2, 0, 2, 1, 1, 0]
low · mid · high0 · 0 · 5
low and mid start at the front and high at the back. The whole array sits between mid and high, the part nobody has looked at yet. The 0s will grow from the left of low and the 2s from the right of high.
lowmidhigh002112unchecked2sswap the 2 to the back → check what came in
nums[0, 0, 2, 1, 1, 2]
low · mid · high0 · 0 · 4
The value at mid is 2, so it swaps with position 5 and the 2s block grows from the right. The value that arrived at mid, 0, came from the unchecked part, so mid stays put and looks at it next.
lowmidhigh0021120sunchecked2s0 is already at the front → grow both
nums[0, 0, 2, 1, 1, 2]
low · mid · high1 · 1 · 4
The value at mid is 0 and it already sits at low, the end of the 0s block, so swapping it with itself changes nothing. Both pointers move right: the 0s block grows by one and the next value gets checked.
lowmidhigh0021120sunchecked2s0 is already at the front → grow both
nums[0, 0, 2, 1, 1, 2]
low · mid · high2 · 2 · 4
The value at mid is 0 and it already sits at low, the end of the 0s block, so swapping it with itself changes nothing. Both pointers move right: the 0s block grows by one and the next value gets checked.
lowmidhigh0011220sunchecked2sswap the 2 to the back → check what came in
nums[0, 0, 1, 1, 2, 2]
low · mid · high2 · 2 · 3
The value at mid is 2, so it swaps with position 4 and the 2s block grows from the right. The value that arrived at mid, 1, came from the unchecked part, so mid stays put and looks at it next.
lowmidhigh0011220s1sunchecked2s1 is already in place → mid steps on
nums[0, 0, 1, 1, 2, 2]
low · mid · high2 · 3 · 3
A 1 belongs in the middle block, which ends just before mid. Moving mid right is enough to include it; nothing needs to swap.
lowmidhigh0011220s1s2s1 is already in place → mid steps on
nums[0, 0, 1, 1, 2, 2]
low · mid · high2 · 4 · 3
A 1 belongs in the middle block, which ends just before mid. Moving mid right is enough to include it; nothing needs to swap.
0011220s1s2smid passed high → sorted
nums[0, 0, 1, 1, 2, 2]
low · mid · high2 · 4 · 3
mid is now past high, so the unchecked part is empty. Every value sits in its block, 0s then 1s then 2s: [0, 0, 1, 1, 2, 2]. Each step either moved mid or shrank high, so the loop ran at most n times.
05

Counting sort for three values

The first loop fills count[0], count[1] and count[2]. The second walks through the colours in order and writes each one as many times as it was counted. It is a good first answer in an interview before you are asked for one pass.

▶1class Solution:
▶2 def sortColors(self, nums):
▶3 count = [0, 0, 0]
▶4 for x in nums:
▶5 count[x] += 1
▶6 i = 0
▶7 for color in range(3):
▶8 for _ in range(count[color]):
▶9 nums[i] = color
▶10 i += 1
06

Common pitfalls

Moving mid after swapping a 2

✗ Wrong
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
mid += 1
✓ Right
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1

On [1, 2, 0] the 2 swaps with the 0, giving [1, 0, 2]. Moving mid now skips that 0, the loop ends, and the result [1, 0, 2] is not sorted.

Stopping when mid reaches high

✗ Wrong
while mid < high:
✓ Right
while mid <= high:

On [1, 0] the 1 moves mid to index 1, which equals high, so the loop quits before the 0 is ever checked and returns [1, 0].

07

Edge cases

Only one colour, such as [2, 2, 2]

Every step swaps a 2 with itself at high and moves high left. The loop ends with high = -1 and the array unchanged, which is already sorted.

08

Complexity

Time
O(n)
Space
O(1)
Every loop either moves mid right or moves high left, so the unchecked zone shrinks by exactly one each time. That gives at most n loops and one pass. Only three index variables are used.
09

Sort Colors FAQ

Why is it called the Dutch national flag problem?

Edsger Dijkstra posed it with balls in the three colours of the Dutch flag, red, white and blue, which had to end up in flag order. The three values here stand for those three stripes.

Is this sort stable?

No. A 2 swapped to the back can jump over other 2s, so equal values change order. Plain integers cannot tell the difference, but if each colour were attached to a record, the order of records with the same colour would not be kept.