π Problem Statement
Given an array arr[] containing only 0s, 1s, and 2s, sort the array in ascending order.
β οΈ Constraint:
You cannot use built-in sorting functions.
π§ͺ Examples
Example 1
Input: [0, 1, 2, 0, 1, 2]
Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
π‘ Optimal Approach: Dutch National Flag Algorithm
This problem can be solved efficiently using the Dutch National Flag Algorithm, which works in:
- β± Time Complexity:
O(n)(single pass) - π¦ Space Complexity:
O(1)(no extra space)
π§ Idea Behind the Algorithm
We divide the array into three regions:
- 0s region β beginning
- 1s region β middle
- 2s region β end
We use three pointers:
-
lowβ position for next0 -
midβ current element -
highβ position for next2
π Algorithm Steps
- Initialize:
low = 0, mid = 0, high = n - 1
- Traverse while
mid <= high:
- If
arr[mid] == 0: β Swaparr[low]andarr[mid], increment bothlowandmid - If
arr[mid] == 1: β Just movemid - If
arr[mid] == 2: β Swaparr[mid]andarr[high], decrementhigh
π» Python Implementation
def sort_array(arr):
low = 0
mid = 0
high = len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else: # arr[mid] == 2
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr
# Example usage
arr = [0, 1, 2, 0, 1, 2]
print(sort_array(arr))
π§Ύ Output
[0, 0, 1, 1, 2, 2]
π Dry Run (Quick Insight)
For input:
[0, 1, 2, 0, 1, 2]
-
0β moved to front -
2β moved to end -
1β stays in middle
- No need for sorting functions β
- Solved in one pass β
- Uses constant space β
- Very common in coding interviews π₯
Top comments (0)