Dutch national flag
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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}); }}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 at4, and decreases by1on every single line (4 -> 3 -> 2 -> 1 -> 0). - When
DONEis reached,0 .. low - 1(0..1) holds0s,low .. high(2..2) holds1s, andhigh + 1 .. n - 1(3..3) holds2s.
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]: all0s (the bottom / red region)nums[low .. mid - 1]: all1s (the middle / white region)nums[mid .. high]: uninspected elements (the unknown region we are shrinking)nums[high + 1 .. n - 1]: all2s (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(or0s).low .. mid - 1: equal topivot(or1s).mid .. high: not yet inspected.high + 1 .. n - 1: strictly> pivot(or2s).
Predict the output
One swap of the flag loop
Work out the printed state.
nums[mid] is a 2. What does this code print?
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.
- Set
low = 0,mid = 0,high = nums.length - 1. - Loop
while (mid <= high). - Case
0: swaplowandmid, thenlow++; mid++;. - Case
1:mid++;. - Case
2: swapmidandhigh, thenhigh--;(leavemidunchanged!).
Dutch National Flag on nums = [2, 0, 2, 1, 1, 0]
Step 1 of 6
- low
- 0
- mid
- 0
- high
- 5
- nums[mid]
- 2
Example 2 · Brute force: sort the whole array (O(n log n) time, O(1) extra space)
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)); }}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.sortsolves 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)
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)); }}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)
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)); }}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], atmid = 0,nums[0] = 2swaps withnums[2] = 1, giving[1, 0, 2]andhigh = 1. Becausemidstays0, the next iteration inspects the newly arrived1atnums[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]:
- If
nums[mid] == 0: Swapnums[low]andnums[mid], then increment bothlow++andmid++. We can advancemidimmediately becausenums[low]was at the start of the1s region (low .. mid - 1), so the value swapped intonums[mid]is guaranteed to be1(orlow == mid, a self-swap). - If
nums[mid] == 1: It already belongs in the middle region. Just incrementmid++. - If
nums[mid] == 2: Swapnums[mid]andnums[high], and decrementhigh--only. Do not incrementmid:nums[high]came from the unknown region, so the value now atnums[mid]has never been inspected (it could be a2, a0or a1) 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
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)); }}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 in0 .. 2, all three5s sit in3 .. 5, and all elements> 5([8, 9]) sit in6 .. 7. - Returning
[low, high]tells 3-way QuickSort to recurse only on0 .. low - 1andhigh + 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→ swaplowandmid,low++; mid++;nums[mid] == pivot→mid++;nums[mid] > pivot→ swapmidandhigh,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!
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