Dutch National Flag Problem: 3-Way In-Place Partitioning in a Single Pass
The Dutch National Flag (DNF) Algorithm, designed by Edsger Dijkstra, partitions an array containing only three distinct keys (typically 0, 1, and 2) into sorted order in a single pass ($O(n)$ time) and strictly $O(1)$ auxiliary memory.
A standard counting sort solves this with two passes (one to tally frequencies, another to overwrite). The DNF algorithm does it in one pass by maintaining four contiguous array sections using three boundary pointers.
The Four Partition Zones and Loop Invariants
The algorithm divides the array into four regions using pointers low, mid, and high:
+---------------+---------------+-----------------+---------------+
| 0s | 1s | Unexamined | 2s |
+---------------+---------------+-----------------+---------------+
0 low-1 low mid-1 mid high high+1 n-1
- Zone 1 (
0tolow - 1): Contains strictly0s (red). - Zone 2 (
lowtomid - 1): Contains strictly1s (white). - Zone 3 (
midtohigh): Contains unexamined elements yet to be sorted. - Zone 4 (
high + 1ton - 1): Contains strictly2s (blue).
Termination Condition: The sorting process concludes when mid > high, which shrinks the unexamined zone to zero elements.
Pointer Movement Rules
Initialize: low = 0, mid = 0, high = n - 1.
Inspect nums[mid] at each step:
-
If
nums[mid] == 0:- Swap
nums[low]andnums[mid]. - Increment both pointers:
low++,mid++. - Why increment
mid? The value swapped fromnums[low]intonums[mid]is guaranteed to be a1(ornums[low]andnums[mid]pointed to the exact same index0), which has already been evaluated.
- Swap
-
If
nums[mid] == 1:- It is already in the correct middle region.
- Simply advance the scanning pointer:
mid++.
-
If
nums[mid] == 2:- Swap
nums[mid]andnums[high]. - Decrement the upper bound:
high--. - Do NOT increment
mid: The new element brought intonums[mid]fromnums[high]was previously unexamined. It could be a0,1, or2, so it must be evaluated on the very next iteration.
- Swap
Trace Walkthrough: nums = [2, 0, 2, 1, 1, 0]
- Start:
low = 0,mid = 0,high = 5
| Step | nums[mid] |
Action | Array After Action | New Pointers |
|---|---|---|---|---|
| 0 | nums[0] = 2 |
Swap with high (5), high-- |
[0, 0, 2, 1, 1, 2] |
low=0, mid=0, high=4 |
| 1 | nums[0] = 0 |
Swap with low (0), low++, mid++ |
[0, 0, 2, 1, 1, 2] |
low=1, mid=1, high=4 |
| 2 | nums[1] = 0 |
Swap with low (1), low++, mid++ |
[0, 0, 2, 1, 1, 2] |
low=2, mid=2, high=4 |
| 3 | nums[2] = 2 |
Swap with high (4), high-- |
[0, 0, 1, 1, 2, 2] |
low=2, mid=2, high=3 |
| 4 | nums[2] = 1 |
Correct zone; advance mid++ |
[0, 0, 1, 1, 2, 2] |
low=2, mid=3, high=3 |
| 5 | nums[3] = 1 |
Correct zone; advance mid++ |
[0, 0, 1, 1, 2, 2] |
low=2, mid=4, high=3 |
mid($4$) $> \text{high}$ ($3$) $\implies$ Loop terminates with[0, 0, 1, 1, 2, 2].
Implementation (C++ and Python)
C++ Implementation
#include <vector>
#include <algorithm>
void sortColors(std::vector<int>& nums) {
int low = 0;
int mid = 0;
int high = nums.size() - 1;
while (mid <= high) {
if (nums[mid] == 0) {
std::swap(nums[low], nums[mid]);
low++;
mid++;
} else if (nums[mid] == 1) {
mid++;
} else { // nums[mid] == 2
std::swap(nums[mid], nums[high]);
high--;
// mid is not incremented; re-evaluate the swapped element
}
}
}
Python Implementation
def sort_colors(nums: list[int]) -> None:
"""
Sorts nums containing 0s, 1s, and 2s in-place in a single pass.
"""
low = 0
mid = 0
high = 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] == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1
# Do not increment mid here
Complexity Analysis
| Metric | Complexity | Explanation |
|---|---|---|
| Time Complexity | $O(n)$ | At each step of the while loop, either mid increments or high decrements. The unexamined range $[mid, high]$ decreases in size by at least $1$ per operation. The total number of iterations is strictly bounded by $n$. |
| Auxiliary Space | $O(1)$ | Rearrangement is performed strictly in-place with three integer index variables. |
Application in Quicksort (3-Way Partitioning)
The primary industrial application of this algorithm is in Bentley-McIlroy 3-way Quicksort (fat pivot partitioning). When an input array contains a significant number of duplicate keys, standard 2-way Lomuto or Hoare partitioning degrades toward $O(n^2)$.
By replacing 2-way partitioning with Dijkstra’s 3-way partition:
- Left partition: elements $< \text{pivot}$
- Middle partition: elements $== \text{pivot}$
- Right partition: elements $> \text{pivot}$
The recursive subproblems completely skip the middle partition, solving arrays with all identical elements in $O(n)$ linear time.
