Skip to lesson

Dutch national flag

If an array contains only 0s, 1s, and 2s (Sort Colors), counting how many of each appear and overwriting the array takes two passes. Edsger Dijkstra's Dutch National Flag algorithm uses three pointers (low, mid, high) to partition the array into three sorted regions in a single O(n) pass with O(1) space.

Three regions with three pointers (the loop invariant)

Partitioning is rearranging an array so that elements of one group come before elements of another, such as all 0s, then 1s, then 2s.

Three pointers split the array into four regions: 0s on the left, 1s next, an unknown middle, and 2s on the right.

Example 1 · Tracing the four regions step by step

DutchFlagTraceDemo.javaJava
import java.util.Arrays;
public class DutchFlagTraceDemo {    public static void trace(int[] nums) {        int low = 0, mid = 0, high = nums.length - 1;        while (mid <= high) {            System.out.printf("low=%d, mid=%d, high=%d | %s%n", low, mid, high, Arrays.toString(nums));            if (nums[mid] == 0) {                int t = nums[low]; nums[low] = nums[mid]; nums[mid] = t;                low++; mid++;            } else if (nums[mid] == 1) {                mid++;            } else {                int t = nums[mid]; nums[mid] = nums[high]; nums[high] = t;                high--;            }        }        System.out.printf("DONE: low=%d, mid=%d, high=%d | %s%n", low, mid, high, Arrays.toString(nums));    }
    public static void main(String[] args) {        trace(new int[]{2, 0, 1, 0});    }}
Output
low=0, mid=0, high=3 | [2, 0, 1, 0]
low=0, mid=0, high=2 | [0, 0, 1, 2]
low=1, mid=1, high=2 | [0, 0, 1, 2]
low=2, mid=2, high=2 | [0, 0, 1, 2]
DONE: low=2, mid=3, high=2 | [0, 0, 1, 2]

What this code does

  • Notice that high - mid + 1 (the count of unknown elements) starts at 4, and decreases by 1 on every single line (4 -> 3 -> 2 -> 1 -> 0).
  • When DONE is reached, 0 .. low - 1 (0..1) holds 0s, low .. high (2..2) holds 1s, and high + 1 .. n - 1 (3..3) holds 2s.

During the scan, we divide the array into four regions using three pointers low = 0, mid = 0, and high = nums.length - 1:

  • nums[0 .. low - 1]: all 0s (the bottom / red region)
  • nums[low .. mid - 1]: all 1s (the middle / white region)
  • nums[mid .. high]: uninspected elements (the unknown region we are shrinking)
  • nums[high + 1 .. n - 1]: all 2s (the top / blue region)

At the start (low = 0, mid = 0, high = n - 1), the 0s, 1s, and 2s regions are empty and the entire array 0 .. n - 1 is unknown. Each step shrinks the unknown region mid .. high by 1 until mid > high, at which point the unknown region is empty and the array is completely partitioned!

  • 0 .. low - 1: strictly < pivot (or 0s).
  • low .. mid - 1: equal to pivot (or 1s).
  • mid .. high: not yet inspected.
  • high + 1 .. n - 1: strictly > pivot (or 2s).

Predict the output

One swap of the flag loop

Work out the printed state.

nums[mid] is a 2. What does this code print?

int[] a = {2, 1, 0};
int mid = 0, high = 2;
int t = a[mid]; a[mid] = a[high]; a[high] = t;
high--;
System.out.println(Arrays.toString(a) + " mid=" + mid + " high=" + high);

Sorting 0s, 1s and 2s in one pass

Each loop step looks at nums[mid] and sends that value to its region with one swap.

  1. Set low = 0, mid = 0, high = nums.length - 1.
  2. Loop while (mid <= high).
  3. Case 0: swap low and mid, then low++; mid++;.
  4. Case 1: mid++;.
  5. Case 2: swap mid and high, then high--; (leave mid unchanged!).

Dutch National Flag on nums = [2, 0, 2, 1, 1, 0]

Step 1 of 6

Array: 2, 0, 2, 1, 1, 0. low at index 0. mid at index 0. high at index 5.
low
0
mid
0
high
5
nums[mid]
2
Start with unknown region 0..5. nums[mid] is 2, so swap mid(0) with high(5) and decrement high-- only (mid stays 0 to inspect the swapped-in value).

Example 2 · Brute force: sort the whole array (O(n log n) time, O(1) extra space)

SortColorsBrute.javaJava
import java.util.Arrays;
public class SortColorsBrute {    public static void sortColors(int[] nums) {        Arrays.sort(nums);    }
    public static void main(String[] args) {        int[] a = {2, 0, 2, 1, 1, 0};        sortColors(a);        System.out.println("Sorted [2,0,2,1,1,0]: " + Arrays.toString(a));
        int[] b = {2, 0, 1};        sortColors(b);        System.out.println("Sorted [2,0,1]:       " + Arrays.toString(b));    }}
Output
Sorted [2,0,2,1,1,0]: [0, 0, 1, 1, 2, 2]
Sorted [2,0,1]:       [0, 1, 2]

What this code does

  • Arrays.sort solves it in one line, but it is a general sort that costs O(n log n) and does not use the fact that only three values exist.
  • With only three values, counting them is enough. That removes the log n factor.

Example 3 · Better: count the values, then rewrite (O(n) time, two passes, O(1) space)

SortColorsCounting.javaJava
import java.util.Arrays;
public class SortColorsCounting {    public static void sortColors(int[] nums) {        int[] count = new int[3];        for (int x : nums) {            count[x]++;        }        int pos = 0;        for (int value = 0; value < 3; value++) {            for (int c = 0; c < count[value]; c++) {                nums[pos++] = value;            }        }    }
    public static void main(String[] args) {        int[] a = {2, 0, 2, 1, 1, 0};        sortColors(a);        System.out.println("Sorted [2,0,2,1,1,0]: " + Arrays.toString(a));
        int[] b = {2, 0, 1};        sortColors(b);        System.out.println("Sorted [2,0,1]:       " + Arrays.toString(b));    }}
Output
Sorted [2,0,2,1,1,0]: [0, 0, 1, 1, 2, 2]
Sorted [2,0,1]:       [0, 1, 2]

What this code does

  • The first pass counts how many 0s, 1s and 2s exist; the second pass writes them back in order. Total work is about 2n steps.
  • It is faster than sorting because counting needs no comparisons between elements. It still reads the array twice; the three-pointer version needs only one pass.

Example 4 · Optimal: three pointers, one pass (O(n) time, O(1) space)

SortColorsDemo.javaJava
import java.util.Arrays;
public class SortColorsDemo {    public static void sortColors(int[] nums) {        int low = 0, mid = 0, high = nums.length - 1;        while (mid <= high) {            if (nums[mid] == 0) {                int temp = nums[low];                nums[low] = nums[mid];                nums[mid] = temp;                low++;                mid++;            } else if (nums[mid] == 1) {                mid++;            } else {                int temp = nums[mid];                nums[mid] = nums[high];                nums[high] = temp;                high--;            }        }    }
    public static void main(String[] args) {        int[] a = {2, 0, 2, 1, 1, 0};        sortColors(a);        System.out.println("Sorted [2,0,2,1,1,0]: " + Arrays.toString(a));
        int[] b = {2, 0, 1};        sortColors(b);        System.out.println("Sorted [2,0,1]:       " + Arrays.toString(b));    }}
Output
Sorted [2,0,2,1,1,0]: [0, 0, 1, 1, 2, 2]
Sorted [2,0,1]:       [0, 1, 2]

What this code does

  • On [2, 0, 1], at mid = 0, nums[0] = 2 swaps with nums[2] = 1, giving [1, 0, 2] and high = 1. Because mid stays 0, the next iteration inspects the newly arrived 1 at nums[0].
  • The loop terminates as soon as mid > high, having inspected every element once.
  • Why it is faster than counting: each element is moved straight to its final region as soon as it is read, so the array is scanned once instead of twice.

In each iteration of while (mid <= high), inspect nums[mid]:

  1. If nums[mid] == 0: Swap nums[low] and nums[mid], then increment both low++ and mid++. We can advance mid immediately because nums[low] was at the start of the 1s region (low .. mid - 1), so the value swapped into nums[mid] is guaranteed to be 1 (or low == mid, a self-swap).
  2. If nums[mid] == 1: It already belongs in the middle region. Just increment mid++.
  3. If nums[mid] == 2: Swap nums[mid] and nums[high], and decrement high-- only. Do not increment mid: nums[high] came from the unknown region, so the value now at nums[mid] has never been inspected (it could be a 2, a 0 or a 1) and must be checked on the next iteration.

Partitioning around any pivot (3-way QuickSort partition)

The Dutch National Flag algorithm is not limited to 0, 1, and 2.

Example 5 · 3-way partitioning around a pivot value

ThreeWayPivotDemo.javaJava
import java.util.Arrays;
public class ThreeWayPivotDemo {    // Returns {low, high}: the inclusive bounds of the == pivot region    public static int[] partition3Way(int[] nums, int pivot) {        int low = 0, mid = 0, high = nums.length - 1;        while (mid <= high) {            if (nums[mid] < pivot) {                int temp = nums[low];                nums[low] = nums[mid];                nums[mid] = temp;                low++;                mid++;            } else if (nums[mid] == pivot) {                mid++;            } else {                int temp = nums[mid];                nums[mid] = nums[high];                nums[high] = temp;                high--;            }        }        return new int[]{low, high};    }
    public static void main(String[] args) {        int[] nums = {9, 4, 5, 2, 5, 8, 5, 1};        int[] eqRange = partition3Way(nums, 5);        System.out.println("Partitioned around 5: " + Arrays.toString(nums));        System.out.println("Equal-to-5 index range: " + Arrays.toString(eqRange));    }}
Output
Partitioned around 5: [1, 4, 2, 5, 5, 5, 8, 9]
Equal-to-5 index range: [3, 5]

What this code does

  • All elements < 5 ([1, 4, 2]) end up in 0 .. 2, all three 5s sit in 3 .. 5, and all elements > 5 ([8, 9]) sit in 6 .. 7.
  • Returning [low, high] tells 3-way QuickSort to recurse only on 0 .. low - 1 and high + 1 .. n - 1.

Given any pivot value pivot (or a range [lowVal, highVal] in Three-Way Range Partitioning), replace the three cases with:

  • nums[mid] < pivot → swap low and mid, low++; mid++;
  • nums[mid] == pivot → mid++;
  • nums[mid] > pivot → swap mid and high, high--;

In 3-Way QuickSort, partitioning around pivot groups all duplicate copies of pivot into nums[low .. high] in a single pass. Unlike standard 2-way QuickSort (which degrades to O(n²) when all elements are equal), 3-way QuickSort never recurses on the equal middle region [low .. high], finishing in O(n) time on arrays with many duplicates!

Remember the golden rule of Dutch National Flag: advance mid after swapping with low, but NEVER advance mid after swapping with high, because nums[high] was uninspected.

Next step

Check your understanding

10 quick questions