Dutch National Flag (Sort Colors)

Sort an array of 0s, 1s and 2s in a single pass, in place, with three markers.

Given an array nums that holds only the values 0, 1 and 2, sort it so that all the 0s come first, then the 1s, then the 2s. Sort it in place: rearrange the values inside nums itself, without copying them into a second array. The problem is also known as Sort Colors, where 0, 1 and 2 stand for red, white and blue.

Example 1
Input: [2, 0, 2, 1, 1, 0] → Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: [2, 0, 1] → Output: [0, 1, 2]
Solution

The Idea

The flag of the Netherlands has three bands: red, white and blue. Picture a shuffled row of red, white and blue cards that you want to lay out like that flag, red on the left, white in the middle, blue on the right. The Dutch computer scientist Edsger Dijkstra posed the problem this way, which is where its name comes from. In the array, red is 0, white is 1 and blue is 2.

Any general sorting method would do the job, but this array is unusual: it holds only three different values. Each value already tells you where it belongs. A 0 goes to the left end, a 2 goes to the right end, and a 1 goes in between. So can every value be put in its place in a single walk through the array?

Try it on Example 1, [2, 0, 2, 1, 1, 0], with three markers. The marker lo shows the spot where the next 0 should go, and starts at index 0. The marker hi shows the spot where the next 2 should go, and starts at the last index, 5. The third marker, mid, walks from the left, starting at index 0, and checks one value at a time.

The three markers split the array into four regions. The 0s sit left of lo, and the 1s from lo up to just before mid. The values not checked yet run from mid to hi, and the 2s sit right of hi. The picture shows Example 1 after each of the six steps, with each region in its own colour.

Example 1, [2, 0, 2, 1, 1, 0], after each of six steps. Blue cells are 0s left of lo, teal cells are 1s from lo up to mid, white cells are not checked yet, grey cells are 2s right of hi. The last row is [0, 0, 1, 1, 2, 2] with mid past hi.

In the row labelled start, every cell is white, because nothing has been checked yet. The value at mid, outlined in orange, is a 2. It is swapped with the value at hi, index 5, and hi moves back one place. Row 1, "saw 2: swap with hi", shows that 2 in grey at index 5, settled for good.

The swap brought the 0 from index 5 to index 0, and it still has the orange outline. The marker mid stayed where it was, because that 0 came from the white region and has not been checked. In rows 2 and 3, mid sees a 0 each time. Each 0 is swapped with the value at lo, here with itself, since lo and mid share an index. Then both markers move on, and the blue region grows.

Row 4 sends the 2 at index 2 to index 4 and brings back a 1. In rows 5 and 6, mid sees a 1, which already belongs just before mid, so only mid moves and the teal region grows. In row 6, mid is at index 4 and hi at index 3. The white region is empty, and the array reads [0, 0, 1, 1, 2, 2].

Each step either moved mid forward or moved hi back, so the white region lost one cell per step. That is the whole idea: the blue and teal regions grow from the left, the grey region grows from the right, and the white region between them shrinks until nothing is left to check.

Solution Approach

A simpler way counts the values in two passes. The one-pass walk needs three decisions: what to do with each value at mid, why mid waits after a swap with hi, and when to stop.

Counting first, in two passes

Is a full sort needed at all? A general sort such as Arrays.sort takes O(n log n) time for n values. With only three values, counting is enough. One pass counts two 0s, two 1s and two 2s in Example 1, and a second pass writes two 0s, two 1s and two 2s back into the array.

That takes O(n) time too, but it reads the array twice and writes new numbers over the old ones instead of moving them. If each value were the colour of a larger record, writing a 0 would not bring the record along. The walk in the picture moves the values themselves with swaps, in one pass.

Handling a 0, a 1 and a 2

What should happen to the value at mid? A 0 belongs at lo, so swap it with the value there and move both lo and mid forward. The value that comes back from lo was checked earlier. When lo is behind mid, it is a 1 from the teal region, and when they share an index, it is the same 0.

A 1 is already in the right place, because the teal region ends just before mid. Moving mid forward adds the 1 to it. A 2 belongs at hi, so swap it with the value there and move hi back.

Why mid waits after a swap with hi

Why not move mid forward after a 2 as well? The value that arrives from hi comes from the white region, so nobody has checked it. In row 1 of the picture it is the 0 from index 5, which still has to go to lo. A version that moves mid anyway turns [1, 2, 0] into [1, 0, 2]: the 0 that came back from the end is skipped and stays behind the 1.

When the walk stops

How long does the walk go on? As long as mid <= hi, because then the white region still has at least one cell. Stopping at mid < hi would leave the last white cell unchecked. With that condition, [1, 0] stays [1, 0]: mid steps past the 1 onto the 0, meets hi, and the loop ends.

Java Solution

The method sortColors works in these steps:

  1. First, set the three markers: lo and mid start at index 0, and hi starts at nums.length - 1, the last index. The comment beside each one says which region it closes off.
  2. Then a while loop runs as long as mid <= hi, that is, while some value is still unchecked. Each time round, it looks at nums[mid].
  3. For a 0, it calls the helper swap(nums, lo, mid), which exchanges the values at two indexes of the array, and moves lo and mid forward.
  4. For a 1, it only moves mid forward.
  5. For a 2, it calls swap(nums, mid, hi) and moves hi back, leaving mid on the value that just arrived.
  6. When the loop ends, the method has nothing to return, because it has rearranged nums itself.

The main method sorts both examples, an empty array, a single 1, an array of only 2s, and [2, 2, 1, 1, 0, 0], the reverse of sorted order, printing each array before and after.

Java
import java.util.Arrays;

public class SortColors {

    public static void sortColors(int[] nums) {
        int lo = 0;                  // nums[0 .. lo-1] are all 0
        int mid = 0;                 // nums[lo .. mid-1] are all 1
        int hi = nums.length - 1;    // nums[hi+1 .. n-1] are all 2
        while (mid <= hi) {
            if (nums[mid] == 0) {
                swap(nums, lo, mid);
                lo++;
                mid++;
            } else if (nums[mid] == 1) {
                mid++;
            } else {
                swap(nums, mid, hi);
                hi--;                // mid stays: the value swapped in is not checked yet
            }
        }
    }

    private static void swap(int[] nums, int a, int b) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {2, 0, 2, 1, 1, 0},
            {2, 0, 1},
            {},
            {1},
            {2, 2, 2},
            {2, 2, 1, 1, 0, 0},
        };
        for (int[] nums : inputs) {
            String before = Arrays.toString(nums);
            sortColors(nums);
            System.out.println(before + " -> " + Arrays.toString(nums));
        }
    }
}

Running it prints:

Output
[2, 0, 2, 1, 1, 0] -> [0, 0, 1, 1, 2, 2]
[2, 0, 1] -> [0, 1, 2]
[] -> []
[1] -> [1]
[2, 2, 2] -> [2, 2, 2]
[2, 2, 1, 1, 0, 0] -> [0, 0, 1, 1, 2, 2]

Both examples come out as expected: [0, 0, 1, 1, 2, 2] after the six steps in the picture, and [0, 1, 2]. The empty array prints [] -> [] without an error, because hi starts at -1, so mid <= hi is false and the loop never runs.

Now look at [2, 2, 2] -> [2, 2, 2]. Here mid never leaves index 0. Every step finds a 2 there, swaps it with the value at hi, which is also a 2, and moves hi back, until hi reaches -1 after three steps. The last line, the reverse of sorted order, comes out sorted as well. A run that counts the work shows it took six steps and four swaps, the same as Example 1.

Would two equal values keep their starting order? Look back at the picture. The 0 that starts at index 5 ends at index 0, ahead of the 0 that starts at index 1. The 2 that starts at index 0 ends at index 5, behind the 2 from index 2. So the sort is not stable: equal values can trade places. For plain numbers it makes no difference, since one 0 cannot be told from another.

Complexity

Every step of the loop shrinks the unchecked region by one cell, and nothing grows with the input except the array itself.

  • Time: O(n) in the best, average and worst case, because each step moves mid forward or hi back, so the loop runs exactly n times for n values in any order. The order only changes the number of swaps: on six values, a run made none for only 1s, four for Example 1, and six for only 0s or only 2s.
  • Space: O(1), because the sort works in place, keeping just the three markers and the one temporary value inside swap.

The same split into "less than, equal to, greater than" helps quicksort on arrays with many repeated values, since all the values equal to the chosen one are settled in one pass.