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 without using a library sort function.

Constraints: O(n) time, O(1) extra space.

Example: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2]

Approach: Use the Dutch National Flag algorithm with three pointers - low, mid, high. Walk mid through the array: if arr[mid]==0, swap with arr[low] and advance both low and mid; if arr[mid]==1, just advance mid; if arr[mid]==2, swap with arr[high] and decrement high (without advancing mid, since the swapped-in value needs re-checking). Terminate when mid > high.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account