๐ 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)