Sort an array of 0s, 1s and 2s
Problem Statement:β
Given an array consisting of only 0s, 1s, and 2s. Write a program to in-place sort the array without using inbuilt sort functions. ( Expected: Single pass-O(N) and constant space)
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Input: nums = [2,0,1]
Output: [0,1,2]
Input: nums = [0]
Output: [0]
β Solution: Dutch National Flag Algorithmβ
void sort012(vector<int>& array) {
int zeroPointer = 0; // Tracks boundary for 0s
int onePointer = 0; // Current element under consideration
int twoPointer = array.size() - 1; // Tracks boundary for 2s
// Loop until mid crosses high
while (onePointer <= twoPointer) {
if (array[onePointer] == 0) {
// Place 0s at the beginning
swap(array[onePointer], array[zeroPointer]);
zeroPointer++;
onePointer++;
} else if (array[onePointer] == 1) {
// 1s stay in the middle
onePointer++;
} else {
// Place 2s at the end
swap(array[onePointer], array[twoPointer]);
twoPointer--;
// Don't increment onePointer here because the swapped element needs to be checked
}
}
}
π How It Worksβ
- This is a three-pointer approach (also called the Dutch National Flag Algorithm).
- The goal is to sort the array with only 0s, 1s, and 2s in one pass (O(n)).
- We divide the array into three parts:
- From
[0 to zeroPointer - 1]: All 0s - From
[zeroPointer to onePointer - 1]: All 1s - From
[twoPointer + 1 to end]: All 2s
- From
- Every element is checked only once.
π§© Key Insightβ
- Donβt increment
onePointerwhen a 2 is encountered and swapped β the swapped value may not be in the correct position and needs rechecking.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| β± Time | O(n) |
| π Space | O(1) |
β οΈ Edge Casesβ
- All elements are already sorted β handled
- All elements are the same (all 0s, all 2s) β handled
- Empty array β no iteration happens
- Array of size 1 β works fine
π‘ Other Approachesβ
| Approach | Time | Space | Notes |
|---|---|---|---|
| Counting Sort | O(n) | O(1) | 2 passes, but fast |
| Dutch Flag (this) | O(n) | O(1) | β Single pass |
| std::sort | O(n log n) | O(1) | β Overkill here |
π Related Problemsβ
π¬