Given an array with values 0, 1 and 2 (red, white and blue), sort it in place so that equal values are adjacent and in the order 0, 1, 2, without using a library sort.
Before you code
Counting sort works in two passes. The one-pass version partitions around the value 1 into three regions: less than, equal to and greater than the pivot, exactly the three-way partition quick sort uses for duplicates.
Hints
- Keep three indexes:
low(end of the 0s),mid(current element) andhigh(start of the 2s). - If
nums[mid]is 0, swap it withnums[low]and advance both. If it is 1, advancemid. If it is 2, swap it withnums[high]and decreasehigh, without advancingmid: the swapped-in value hasn't been examined. - Stop when
mid > high.
Production & complexity notes
When solving Sort colors on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Quick sort and partitioning to reinforce the underlying pattern.
What it practices
The three-way partition, from Quick sort and partitioning.