0:00 / 0:00

Sort an array of 0s, 1s and 2s in one pass: three pointers sweep zeros to the front and twos to the back, leaving ones in the middle.

▼

The problem

LeetCode 75 (Medium). Given an array nums of n values, each 0, 1 or 2 (red, white and blue), sort it in place so that equal colours are adjacent, in the order 0, 1, 2, without the library's sort. The follow-up asks for one pass and constant extra space.

Example (the video's): nums = [1, 2, 0, 2, 1, 0] → [0, 0, 1, 1, 2, 2].

TRY IT ON LEETCODE ▶

The solution

def sort_colors(nums):
    low, mid, high = 0, 0, len(nums) - 1
    while mid <= high:
        if nums[mid] == 0:
            nums[low], nums[mid] = nums[mid], nums[low]
            low += 1
            mid += 1
        elif nums[mid] == 1:
            mid += 1
        else:
            nums[mid], nums[high] = nums[high], nums[mid]
            high -= 1

Transcript

Sort Colors. A row of nest boxes holds eggs marked zero, one or two: red, white and blue. Sort them in place, so the reds come first, then the whites, then the blues, without a library sort.

Take one, two, zero, two, one, zero. Sorted, it reads zero, zero, one, one, two, two. Same eggs, same boxes, just a new order.

The easy way is counting: two zeros, two ones, two twos, then rewrite the row. That's linear time, but it takes two passes. The follow-up asks for one pass and constant extra space.

The trick is Dijkstra's Dutch national flag: three stripes, and three pointers. Everything before low is a zero. Everything after high is a two. From low up to mid sit the ones. And from mid to high is the unknown, still to be checked.

Mid looks at one egg at a time. A zero swaps with the egg at low, and both pointers move up. A one is already in place, so mid just moves on. A two swaps with the egg at high, and high moves down. But mid stays put, because the egg it got back hasn't been checked yet.

In code, that's one loop that runs while mid is at most high, with three branches: zero, one and two.

Let's run it. Mid sees a one and steps past it. Then a two: it swaps with the zero at the end, and high steps in. Mid stays and checks that zero: it swaps with the one at low, and both advance. Another zero swaps with that one. The next two swaps with the one at high. Mid checks that one, steps on, and passes high. Done: zero, zero, one, one, two, two.

Each step either moves mid up or moves high down, so the unknown shrinks by one every time. Six eggs, six steps: order n time, in a single pass, and order one space, just three pointers.

Zeros to the front, twos to the back, ones in the middle. That's Sort Colors.