Arrays & Hashing · Pattern 9 of 26
Dutch national flag: three-way partition
Three regions grow at once: 0s on the left, 2s on the right, 1s in the middle, and an unknown part shrinking between them. One pass, in place.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Sort an array with only three distinct values
- Partition around a pivot into less, equal and greater
The template
void sortColors(int[] a) {
int lo = 0, mid = 0, hi = a.length - 1; // [0,lo) 0s, [lo,mid) 1s, (hi,end] 2s
while (mid <= hi) {
if (a[mid] == 0) { int t = a[lo]; a[lo++] = a[mid]; a[mid++] = t; }
else if (a[mid] == 1) mid++;
else { int t = a[hi]; a[hi--] = a[mid]; a[mid] = t; } // do not move mid
}
} def sort_colors(a):
lo, mid, hi = 0, 0, len(a) - 1 # [0,lo) 0s, [lo,mid) 1s, (hi,end] 2s
while mid <= hi:
if a[mid] == 0:
a[lo], a[mid] = a[mid], a[lo]
lo += 1; mid += 1
elif a[mid] == 1:
mid += 1
else:
a[mid], a[hi] = a[hi], a[mid]
hi -= 1 # do not move mid: the swapped value is unchecked void sortColors(vector<int>& a) {
int lo = 0, mid = 0, hi = (int)a.size() - 1; // [0,lo) 0s, [lo,mid) 1s, (hi,end] 2s
while (mid <= hi) {
if (a[mid] == 0) swap(a[lo++], a[mid++]);
else if (a[mid] == 1) mid++;
else swap(a[mid], a[hi--]); // do not move mid
}
} function sortColors(a) {
let lo = 0, mid = 0, hi = a.length - 1; // [0,lo) 0s, [lo,mid) 1s, (hi,end] 2s
while (mid <= hi) {
if (a[mid] === 0) { [a[lo], a[mid]] = [a[mid], a[lo]]; lo++; mid++; }
else if (a[mid] === 1) mid++;
else { [a[mid], a[hi]] = [a[hi], a[mid]]; hi--; } // do not move mid
}
} The variations
-
1Three regions with three pointers
Swap 0s to the front and 2s to the back; 1s stay where they are. Counting sort also works, but needs two passes.
Mistakes to avoid
- Advancing
midafter swapping withhi: the value that came from the right has not been checked. - Looping while
mid < hiand missing the last element.
Lesson done
Next: Prefix sums →Mark it done once you can write the template from memory and you have solved the worked examples yourself.