Learn / Arrays

Dutch national flag

Split an array into three groups in one pass with three pointers. Everything before low is in the first group, everything after high is in the last, and mid walks the unknown part in between, sending each value to its group with at most one swap.

How to recognise it

  • The values fall into exactly three groups (0, 1, 2; below, inside, above a range; less, equal, greater than a pivot).
  • You must rearrange in place, in one pass, with O(1) extra memory.
  • Sorting an array with very few distinct values, or with many repeats.

The idea in one picture

Picture the Dutch flag: red, white, blue bands. You have a row of shuffled coloured tiles and want the three bands. Keep the red band growing from the left and the blue band growing from the right. One finger (mid) walks through the unsorted tiles in the middle. A red tile is swapped to the end of the red band, a blue tile to the front of the blue band, and a white tile just stays. Each tile is handled once, so the whole job is one pass.

The invariant

RegionHolds
0 .. low - 1first group
low .. mid - 1middle group
mid .. highnot looked at yet
high + 1 .. n - 1last group

Template

low = 0, mid = 0, high = n - 1
while mid <= high:
    if nums[mid] is in the first group:
        swap nums[low], nums[mid]; low = low + 1; mid = mid + 1
    else if nums[mid] is in the last group:
        swap nums[mid], nums[high]; high = high - 1      # mid stays: new value is unknown
    else:
        mid = mid + 1

A guided example: sort [2, 0, 2, 1, 1, 0]

steplowmidhigharrayaction
1005[2, 0, 2, 1, 1, 0]2: swap with high
2004[0, 0, 2, 1, 1, 2]0: swap with low
3114[0, 0, 2, 1, 1, 2]0: swap with low
4224[0, 0, 2, 1, 1, 2]2: swap with high
5223[0, 0, 1, 1, 2, 2]1: move on
6233[0, 0, 1, 1, 2, 2]1: move on, done

Common mistakes

  • Moving mid forwards after swapping with high, which skips a value that was never checked.
  • Looping while mid < high instead of mid <= high, which leaves the last unknown value unchecked.
  • Counting the three values and rewriting the array. That works for 0, 1, 2 but needs two passes, and it fails when the groups are ranges of different values that must be kept.

Problems

0 of 3 solved

Check yourself

mid sees a value that belongs in the last group and swaps it with high. Why does mid not move forwards afterwards?

mid sees a first-group value and swaps it with low. Why can mid move forwards this time?

What do the three pointers guarantee at every moment?

Why does three-way partitioning help quicksort on arrays with many repeated values?