The Dutch National Flag problem. [2,0,1,2,0,1,0,2] → [0,0,0,1,1,2,2,2].
(LeetCode 75)
Brute force: run any general sort — O(n log n), unnecessary given only 3 distinct values.
Better — counting: count zeros, ones, and twos in one pass, then overwrite the array with that many 0s, then 1s, then 2s.
Optimal — Dutch National Flag algorithm, three pointers: low marks the boundary between 0s
and 1s, mid is the element currently being processed, high marks the boundary between 1s and
2s.
arr[mid] == 0: swap witharr[low], advance bothlowandmid(the 0 is now placed).arr[mid] == 1: already in the right zone, just advancemid.arr[mid] == 2: swap witharr[high], decrementhigh— but don’t advancemid, since the newly-swapped-in element atmidhasn’t been checked yet.
Continue until mid passes high. Time: O(n), single pass. Space: O(1), sorted in place.