Problem
Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order without using any built-in sort function.
My Thought Process
At first, this looks like a normal sorting problem.
But since using built-in sort is not allowed, I needed to think differently.
The key observation is that the array contains only three distinct values.
So instead of general sorting, I can group the elements.
Approach (Dutch National Flag Algorithm)
I used three pointers:
-
low→ position for0s -
mid→ current index -
high→ position for2s
Logic
If
arr[mid] == 0
Swap withlow, then increment bothlowandmidIf
arr[mid] == 1
Just incrementmidIf
arr[mid] == 2
Swap withhigh, then decrementhigh
Code
class Solution {
public void sort012(int[] arr) {
int low = 0, mid = 0, high = arr.length - 1;
while (mid <= high) {
if (arr[mid] == 0) {
int temp = arr[low];
arr[low] = arr[mid];
arr[mid] = temp;
low++;
mid++;
}
else if (arr[mid] == 1) {
mid++;
}
else {
int temp = arr[mid];
arr[mid] = arr[high];
arr[high] = temp;
high--;
}
}
}
}
Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
Key Takeaway
This problem is a classic example of the three-pointer technique.
Instead of applying general sorting, understanding the constraints helps in designing an optimal solution.
--
Top comments (0)