Problem Explanation
You are given an array that contains only 0s, 1s, and 2s.
Your task is to sort the array in ascending order without using any built-in sort function.
Example:
- Input:
arr = [0, 1, 2, 0, 1, 2]Output:[0, 0, 1, 1, 2, 2]
Idea Behind the Solution
Instead of comparing and swapping elements, we do something smarter:
- Count how many 0s, 1s, and 2s are present
- Rewrite the array using those counts
This avoids unnecessary operations and keeps the logic simple.
Python Code with Explanation
class Solution:
def sort012(self, arr):
count0 = 0
We create a variable count0 to store how many times 0 appears in the array.
count1 = 0
This variable stores how many times 1 appears.
count2 = 0
This variable stores how many times 2 appears.
for num in arr:
We loop through each element in the array one by one.
if num == 0:
count0 += 1
If the element is 0, we increase the count of 0s.
elif num == 1:
count1 += 1
If the element is 1, we increase the count of 1s.
else:
count2 += 1
If it's not 0 or 1, it must be 2, so we increase the count of 2s.
Now we know how many 0s, 1s, and 2s are present.
index = 0
We start filling the array from index 0.
for i in range(count0):
arr[index] = 0
index += 1
We fill the array with all the 0s first.
Each time we place a 0, we move to the next index.
for i in range(count1):
arr[index] = 1
index += 1
Next, we fill all the 1s.
for i in range(count2):
arr[index] = 2
index += 1
Finally, we fill all the 2s.
return arr
We return the sorted array.
Complete Code (Final)
class Solution:
def sort012(self, arr):
count0 = 0
count1 = 0
count2 = 0
for num in arr:
if num == 0:
count0 += 1
elif num == 1:
count1 += 1
else:
count2 += 1
index = 0
for i in range(count0):
arr[index] = 0
index += 1
for i in range(count1):
arr[index] = 1
index += 1
for i in range(count2):
arr[index] = 2
index += 1
return arr
Step-by-Step Example
Input:
arr = [0, 1, 2, 0, 1, 2]
Step 1: Count
- count0 = 2
- count1 = 2
- count2 = 2
Step 2: Rewrite array
- First 2 positions → 0
- Next 2 positions → 1
- Last 2 positions → 2
Output:
[0, 0, 1, 1, 2, 2]
Time and Space Complexity
- Time Complexity:
O(n)(one pass to count + one pass to fill) - Space Complexity:
O(1)(no extra space used)
Key Takeaway
This method is one of the easiest ways to solve the problem because:
- No swapping is required
- No complex logic
- Just counting and rewriting
Top comments (0)