Originally published byDev.to
Sorting an array containing only 0s, 1s, and 2s is a classic problem in Data Structures.
It is commonly solved using the Dutch National Flag Algorithm, which is highly efficient.
π Problem Statement
Given an array arr[] containing only 0, 1, and 2, sort the array in ascending order without using built-in sort.
π 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]
π§ Concept
We divide the array into three regions:
- Left β all
0s - Middle β all
1s - Right β all
2s
We use three pointers:
-
lowβ position for next0 -
midβ current element -
highβ position for next2
π Approach: One-Pass (Optimal Solution)
Step-by-Step:
- Initialize:
low = 0mid = 0high = n - 1
- Traverse while
mid <= high:
-
If
arr[mid] == 0:- Swap
arr[low]andarr[mid] -
low++,mid++
- Swap
-
If
arr[mid] == 1:- Move
mid++
- Move
-
If
arr[mid] == 2:- Swap
arr[mid]andarr[high] -
high--(do NOT increment mid here)
- Swap
π» Python Code
```python id="c1i8rm"
def sort_012(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
print(sort_012([0, 1, 2, 0, 1, 2]))
---
## π§Ύ Dry Run (Step-by-Step)
For:
```id="m3z2fg"
arr = [0, 1, 2, 0, 1, 2]
| Step | low | mid | high | Array |
|---|---|---|---|---|
| 1 | 0 | 0 | 5 | [0, 1, 2, 0, 1, 2] |
| 2 | 1 | 1 | 5 | [0, 1, 2, 0, 1, 2] |
| 3 | 1 | 1 | 4 | [0, 1, 1, 0, 1, 2] |
| 4 | 1 | 2 | 4 | [0, 1, 1, 0, 1, 2] |
| 5 | 2 | 3 | 4 | [0, 0, 1, 1, 1, 2] |
Final β [0, 0, 1, 1, 2, 2]
β‘ Time and Space Complexity
-
Time Complexity:
O(n)(single traversal) -
Space Complexity:
O(1)(in-place)
π Alternative Approach (Counting Method)
```python id="6qz4ki"
def sort_012(arr):
count0 = arr.count(0)
count1 = arr.count(1)
count2 = arr.count(2)
i = 0
for _ in range(count0):
arr[i] = 0
i += 1
for _ in range(count1):
arr[i] = 1
i += 1
for _ in range(count2):
arr[i] = 2
i += 1
return arr
---
## π§© Where Is This Used?
* Partitioning problems
* QuickSort optimizations
* Interview questions
---
## π Conclusion
The **Dutch National Flag Algorithm** is the best solution for this problem because it:
* Works in **one pass**
* Uses **constant space**
* Is highly efficient
πΊπΈ
More news from United StatesUnited States
NORTH AMERICA
Related News

Open Harness: The Multi-Panel AI Powerhouse Revolutionizing Developer Workflows
10h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
50% of Consumers Prefer Brands That Avoid GenAI Content
9h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
9h ago
CBS News Shutters Radio Service After Nearly a Century
9h ago