Given an array with n objects colored red (0), white (1), and blue (2), sort them in-place so same colors are adjacent, in order: red, white, blue.
This is the famous Dutch National Flag problem by Dijkstra.
Use three pointers: low (boundary for 0s), mid (current), high (boundary for 2s). One pass, O(n) time, O(1) space!
nums[mid] == 0: swap with low, move both forwardnums[mid] == 1: just move mid forwardnums[mid] == 2: swap with high, move high back (don't move mid — the swapped value needs checking)sort_colors([2,0,2,1,1,0])
[0, 0, 1, 1, 2, 2]