A scrambled row of red, white and blue — 0s, 1s and 2s. Sort them into three clean bands. The obvious fix counts each color and rewrites; the beautiful fix uses three pointers in a single in-place sweep, and never touches an element twice unnecessarily. Named for the flag it builds, it’s also the partition that makes quicksort fast when values repeat.
O(n) time · O(1) space · in-place · one pass
low
Everything left of low is a settled 0 (red).
mid
The scanner. Between low and mid sits settled 1s (white).
high
Everything right of high is a settled 2 (blue).
unexplored
The shrinking gap from mid to high — the only region still in question.
sort_colors.js — one pass, three pointers
0 red 1 white 2 blue
Ready
A scrambled flag of 0s, 1s and 2s. Three pointers — low, mid, high — will sort it in one pass. Press Step: we look at arr[mid] and act on its color.
0
low
0
mid
8
high
How it works
The array is always four regions: settled 0s (before low), settled 1s (from low to mid), an unexplored gap (mid to high), and settled 2s (after high). Every step shrinks the gap by examining arr[mid] and doing one of three things — the whole algorithm is a three-way switch.
0
Saw a 0 (red)
Swap it down to low, then advance bothlow and mid. The value coming back is already-examined, so mid can move on.
1
Saw a 1 (white)
It’s already in the right band. Just advance mid.
2
Saw a 2 (blue)
Swap it up to high, then shrink high — but don’t move mid: the value swapped back is from the unexplored gap and must be examined next.
✓
Stop when mid passes high
The gap is empty; the flag is sorted. One pass, no counting, no extra array.
Time
O(n)
Space
O(1)
Passes
1
Stable?
No (it swaps)
The code
# sort an array of 0s, 1s, 2s in place, one passdef sort_colors(a):
low, mid, high = 0, 0, len(a) - 1
while mid <= high:
if a[mid] == 0:
a[low], a[mid] = a[mid], a[low]
low += 1; mid += 1
elif a[mid] == 1:
mid += 1
else: # a[mid] == 2
a[mid], a[high] = a[high], a[mid]
high -= 1 # mid stays!return a
The one asymmetry — mid advances on a 0 but not on a 2 — is the whole subtlety, and the most common bug. A 0 swaps back a value we already sorted; a 2 swaps back a value we haven’t seen. Get that right and the rest is mechanical.
Quick check
1. When arr[mid] is a 2, why doesn’t mid advance after the swap?
Right — swapping with high pulls in an unseen value, so mid must inspect it. Swapping a 0 with low pulls back an already-settled value, so mid can move.
2. Why prefer this over counting the 0s, 1s and 2s?
Both are O(n), but the flag algorithm is single-pass and swaps actual records — important when the values carry payloads you must preserve, not just labels.
FAQ
What is the Dutch national flag problem?
Sorting an array of three distinct values into three contiguous bands — like the red/white/blue of the Dutch flag — in place, in one pass. Named and popularized by Dijkstra.
Does it generalize beyond three values?
The exact three-pointer form is for three groups, but the idea — partition around a pivot value into less-than / equal / greater-than — is the general three-way partition used inside quicksort to handle duplicate keys efficiently.
Is it stable?
No. It swaps elements across the array, so equal elements can change relative order. If you need stability, count-and-rebuild or a stable sort is the trade-off.
Where does it show up in practice?
The classic "sort colors" interview question, and as the partition scheme (three-way / fat-partition quicksort) that keeps quicksort near O(n log n) on inputs with many repeated values.
Prefer a video walkthrough?
Six minutes: why sorting is overkill, the count-and-rewrite detour, three pointers settling the row in one pass, why mid waits after a two, and the follow-ups an interviewer asks next.
The picture: four regions, one shrinking gap
The page’s array [2, 0, 2, 1, 1, 0] after three steps. Everything outside the gap is final: zeros on the left, twos on the right. Only the three cells between mid and high are still unknown.
Worked example, step by step
Start with a = [2, 0, 2, 1, 1, 0], low = mid = 0, high = 5. Each step reads a[mid] (column “Read”) and acts. The array shown is the state after the step.
Step
Read
Action
Array after
low
mid
high
1
2
swap with high
[0, 0, 2, 1, 1, 2]
0
0
4
2
0
swap with low
[0, 0, 2, 1, 1, 2]
1
1
4
3
0
swap with low
[0, 0, 2, 1, 1, 2]
2
2
4
4
2
swap with high
[0, 0, 1, 1, 2, 2]
2
2
3
5
1
advance mid
[0, 0, 1, 1, 2, 2]
2
3
3
6
1
advance mid
[0, 0, 1, 1, 2, 2]
2
4
3
Step 1 reads a 2 and swaps it with the last cell, which brings in a 0 that nobody has looked at, so mid stays at 0. Step 2 reads exactly that 0 and swaps with itself (low = mid), which is harmless and moves both pointers. The asymmetry is visible in step 4: reading a 2 at index 2 swaps in the 1 from index 4, and mid does not move, so step 5 reads that 1 next. Total: 6 steps for 6 elements (each step either advances mid or shrinks high, so the gap closes by one every time), and 4 swaps. The result is [0, 0, 1, 1, 2, 2].
The same sweep on real keys. Replace 0, 1 and 2 with “less than, equal to, greater than a pivot” and you have quicksort’s three-way partition. Take [4, 9, 4, 1, 7, 4, 2] with pivot 4. The sweep ends at [2, 1, 4, 4, 4, 7, 9] after 7 steps and 4 swaps, with low = 2 and high = 4: indices 0–1 hold the smaller keys, 2–4 the three copies of the pivot, and 5–6 the larger keys. The middle band is finished. Quicksort recurses only on [2, 1] and [7, 9], so the three 4s are never compared again.
Complexity and trade-offs
Case
Time
Space
Why
Three-pointer sweep
O(n)
O(1)
The gap shrinks by one every step, so at most n steps. One pass, in place.
Count, then rewrite
O(n)
O(1) for three counters
Two passes. It overwrites labels, so it cannot carry attached records.
Comparison sort
O(n log n)
O(1) to O(log n)
Correct but ignores that only three distinct values exist.
Stable partition (extra arrays)
O(n)
O(n)
Three buckets then concatenate. Keeps order of equals, which the in-place sweep cannot.
Counting sort, k groups
O(n + k)
O(n + k)
The general answer when there are more than three groups; the three-pointer sweep only fits exactly three.
The sweep does at most one swap per step, so at most n swaps. The real cost is instability: on keys [0, 0, 2, 2] tagged with their original positions, the two 2s come out in the order 3, 2. If records with equal keys must keep their original order, use the extra-array version.
Common mistakes
Advancing mid after swapping with high
On [1, 2, 0] the buggy version ends as [1, 0, 2]: the 2 swaps with the 0, mid steps past that 0 without reading it, and it is never moved down. The value from high is unseen, so mid must stay.
Looping while mid < high
The loop must run while mid <= high. With <, the last unexplored cell is skipped: [1, 0] returns unchanged, because mid = 0 and high = 1 stop after one step with the 0 still in the wrong place.
Moving high when you see a 0
Swapping a 0 toward high instead of low puts it in the 2s band. Zeros go to low, twos go to high, ones stay.
Not advancing low with mid on a 0
If low stays put while mid advances, the settled-1 region is mislabelled and the next 0 swaps with the wrong cell, undoing earlier work. They move together on a 0; low never moves on a 1.
Expecting stability
Sorting records by a three-valued key with this sweep can reorder equal keys, as the 2s in [0, 0, 2, 2] show. Do not use it where original order among equals must survive.
Where this shows up
Sort Colors
The textbook form is LeetCode 75 “Sort Colors”: sort an array of 0s, 1s and 2s in place in one pass. The follow-up asks for constant extra space, which is precisely this algorithm.
Quicksort with duplicate keys
Dijkstra posed the problem in 1976 as a model for partitioning. Three-way quicksort partitions into less than, equal to and greater than the pivot, so a run of equal keys is finished in one pass instead of degrading to quadratic time. The JDK’s sort for primitive arrays is a dual-pivot quicksort, a close relative with three zones.
Quickselect
Selecting the k-th smallest element uses the same partition; the equal band means a pivot that appears many times terminates the search immediately.
Bucketing a stream by category
Any in-place grouping into three classes (below, within and above a threshold; negative, zero, positive) is this sweep with a different test on a[mid].
SOLVE IT YOURSELF
Solve it: sort 0s, 1s and 2s in one pass
Three values, one pass, no counting and no sort call. Dijkstra’s three-pointer partition. Write it in Python or TypeScript, running for real in your browser.
YOUR TASK
Implement sort_colors(nums): given a list containing only 0, 1 and 2, return it sorted — in a single pass, using three pointers rather than counting occurrences.
HINTS — 5 IDEAS
Keep three pointers: low (end of the 0s), mid (what you are looking at), high (start of the 2s).
Loop while mid <= high. Everything before low is 0, everything after high is 2.
See a 0: swap it down to low, then advance bothlow and mid.
See a 1: it is already in the middle region — just advance mid.
See a 2: swap it up to high and decrement high — but do not advance mid, because the value you just swapped in is unexamined. That single asymmetry is where almost everyone gets this wrong.