Sort an Array of 0s, 1s, and 2s (Dutch National Flag)
viaGlassdoor
Problem: Given an array containing only 0s, 1s, and 2s, sort it in place in a single pass.
Constraints: In-place, O(1) extra space, single pass preferred.
Example: [2,0,1,2,1,0] -> [0,0,1,1,2,2].
Approach: Dutch National Flag algorithm - maintain three pointers: low (boundary for 0s), mid (current element), high (boundary for 2s). If arr[mid]==0, swap with arr[low], increment both low and mid. If arr[mid]==1, just increment mid. If arr[mid]==2, swap with arr[high], decrement high (don't advance mid, since the swapped-in value needs re-checking). Continue until mid > high. O(n) time, O(1) space.
asked …