Sort Colors

MediumThree Pointers · Dutch National Flag🧩 Partitioning & QuickselectLeetCode #75 ↗Updated

Problem

An array nums holds only the values 0, 1 and 2 (red, white, blue). Rearrange it in-place so all 0s come first, then all 1s, then all 2s — without calling a library sort.
Input[2,0,2,1,1,0]Output[0,0,1,1,2,2]
Input[2,0,1]Output[0,1,2]

1 ≤ n ≤ 300  ·  nums[i] ∈ {0, 1, 2}  ·  Follow-up: one pass with O(1) extra space.

Try it yourself

Java
class Solution {
    public void sortColors(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
With only three keys you can grow the 0-zone from the left and the 2-zone from the right at the same time; whatever stays in the middle is 1. One scan, swaps only.
PatternPartitioning & Quickselect

Instinct Need the k-th smallest/largest, an unordered top-k, or values grouped into buckets in place - partition around a pivot and chase only one side.

Memory hack Pivot, partition, pick a side - quickselect is quicksort's lazy cousin that only chases the half holding k.

Open the Partitioning & Quickselect guide →

Approaches

Brute ForceGeneral Comparison Sort

Time O(n log n)Space O(log n)

Ignore the fact that there are only three values and sort like any integer array (shown here with Arrays.sort, i.e. dual-pivot quicksort; an interviewer will ask you to replace it). Correct, but wastes the tiny key range.

Java
public void sortColors(int[] nums) {
    Arrays.sort(nums);
}

One line and correct, but O(n log n) and violates the “no library sort” rule.

At a glance

LevelApproachTimeSpace
Brute ForceGeneral Comparison SortO(n log n)O(log n)
BetterCounting Sort (Two Passes)O(n)O(1)
OptimalDutch National Flag (low / mid / high)O(n)O(1)
Common pitfalls
  • Incrementing mid after swapping with high — skips an unchecked value.
  • Loop condition mid < high instead of mid ≤ high — misses the last element.
  • Advancing only low on a 0 — the value swapped in is always 1 (or itself), so move both.
Interview tips
  • Mention counting sort first, then improve to one pass for the follow-up.
  • State the four-region invariant before writing code.
  • Trace [2,0,1] to show why mid stays on a high swap.
Pattern
3-way partition (Dutch flag) → group values into <, =, > a pivot (or 3 classes) in one pass.
My notes saved in this browser