Skip to content

visual walkthrough

Sort Colors

MediumDutch National FlagReported at: AmazonMicrosoftMeta+5

Three-way partitioning in one pass; also the core of 3-way quicksort.

Solve on LeetCode

The idea

Keep three regions: 0s on the left, 2s on the right, and an unknown middle that `mid` walks through. A 0 is swapped left, a 2 is swapped right, and a 1 is simply passed over.

Every element is placed at most once, so one pass sorts the whole array.

Complexity

approachtimespace
Count, then rewriteO(n)O(1)
Dutch national flagO(n)O(1)

More walkthroughs