mediumArrayTwo PointersTwo Pointers

Sort Colors

mediumTime: O(n)Space: O(1)

Recognize the pattern

sort array of 0s 1s and 2sDutch national flagthree-way partition

Brute force idea

If you approach Sort Colors in the most literal way possible, you get this: Counting sort (count 0s, 1s, 2s, overwrite) — but two passes. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Sort Colors is this: Dutch National Flag: three pointers — low (next 0 position), mid (current), high (next 2 position). Swap 0s to front, 2s to back, 1s stay in middle. Single pass. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Sort Colors is this: Everything before low is 0, everything after high is 2, everything between low and mid is 1. Mid scans through unsorted elements. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

The trap in Sort Colors usually looks like this: Not incrementing mid when swapping with high — the element swapped from high hasn't been examined yet, so don't advance mid. When swapping with low, both mid and low advance because the swapped element is known to be 1. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Two Pointers Pattern