MediumPythonJavaScriptTypeScript
Sorting — Sort Colors (Dutch National Flag)
AlgorithmsSortingTwo Pointers
solve(nums) — nums only contains 0, 1 and 2. Sort it in place so the
zeros come first, then the ones, then the twos, and return it. Do it in one pass
with constant extra space — no sort(), no counting pass.
Keep three regions with two boundaries and one scanner: everything before low is0, everything after high is 2, and the scanner mid walks the unknown middle.
Examples
solve([2,0,2,1,1,0]) → [0,0,1,1,2,2]
solve([2,0,1]) → [0,1,2]
solve([1,1,1]) → [1,1,1]Sample tests
Test #1Mixed colours
Input: [[2,0,2,1,1,0]]
Output: [0,0,1,1,2,2]
Test #2One of each
Input: [[2,0,1]]
Output: [0,1,2]
Test #3Already uniform
Input: [[1,1,1]]
Output: [1,1,1]