SORTING 0S,1S,2S
Sorting 0s, 1s, and 2s – Dutch National Flag Algorithm
Introduction
This problem involves sorting an array containing only 0s, 1s, and 2s in ascending order. The challenge is to solve it without using built-in sorting functions and ideally in a single pass with constant space.
Problem Statement
Given an array arr[] containing only:
0s
1s
2s
Sort the array in ascending order.
Example
Input:
arr = [0, 1, 2, 0, 1, 2]
Output:
[0, 0, 1, 1, 2, 2]Solution Code
class Solution {
public void sort012(int[] arr) {
int low = 0, mid = 0;
int 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 { // arr[mid] == 2
int temp = arr[mid];
arr[mid] = arr[high];
arr[high] = temp;
high--;
}
}
}
}Approach Used: Dutch National Flag Algorithm
Idea
We divide the array into three parts:
0s region = beginning
1s region = middle
2s region = end
We use three pointers:
low= for placing 0smid= current elementhigh= for placing 2s
How It Works
Initialize:
low = 0,mid = 0,high = n - 1
Traverse while
mid <= high:If
arr[mid] == 0
Swap witharr[low], increment bothlowandmidIf
arr[mid] == 1
Just movemidIf
arr[mid] == 2
Swap witharr[high], decrementhigh
Why This Approach Was Chosen
Solves the problem in one pass (O(n))
Uses constant extra space (O(1))
Much more efficient than sorting (O(n log n))
Specifically designed for arrays with limited values (0,1,2)
Alternative Approaches
Counting approach
Count number of 0s, 1s, 2s and overwrite array
Simple
Requires two passesBuilt-in sort()
Not allowed in this problem
Why Dutch Flag?
Because it satisfies both:
One-pass requirement
Constant space constraint
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Important Observation
When swapping with
high, we do not increment mid
Because the swapped element needs to be checked again
Conclusion
The Dutch National Flag algorithm is an efficient and elegant solution for sorting arrays containing only 0s, 1s, and 2s. It meets all constraints of the problem by performing the task in a single traversal with constant space, making it the optimal approach.
Comments
Post a Comment