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.

1 variation · 1 problem · 1 with animated walkthroughs

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

Dutch National Flag
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
    }
}

The variations

  1. 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 mid after swapping with hi: the value that came from the right has not been checked.
  • Looping while mid < hi and missing the last element.
Next: Prefix sums →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.