Sort Colors
Sort Colors
Problem Statement
You’re given:
-
An array
nums[]of integers, where each value is either:-
0= Red ๐ฅ -
1= White ⚪ -
2= Blue ๐ต
-
You need to sort the array in-place such that the final order is all 0s, followed by 1s, then 2s.
No using .sort()
Example
Input:
nums = [2, 0, 2, 1, 1, 0]
Output:
[0, 0, 1, 1, 2, 2]
Best Data Structure for the Job
Simple arrays do the trick!
No need to pull out HashMaps or fancy data structures — all you need are:
-
Some pointer magic
-
A while loop
-
A sprinkle of swaps
Different Approaches
1) Brute Force (Don't do this in interviews )
Just count how many 0s, 1s, and 2s exist, then rewrite the array.
2) Dutch National Flag Algorithm ๐ณ๐ฑ (Optimal)
We use three pointers:
-
low: points to where the next 0 should go -
mid: current element -
high: where the next 2 should go
We loop through the array once and do swaps on the fly.
⚠️ Common Pitfalls
-
Forgetting that 2s go to the end and we don’t increment
midafter swapping withhigh -
Trying to use a sort function
-
Using extra space , we sort it in-place
๐ Complexity Summary
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Brute Force (count + fill) | O(n) | O(1) |
| Dutch National Flag | O(n) | O(1) |
๐ Real-World Use Cases
-
Sorting categorized tickets (e.g., priority levels: high, medium, low)
-
Token-based traffic management (based on 3 priority levels)
-
Color-coded medical alert systems
I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!
Signing off!!
Master DSA One Problem at a Time :)
Comments
Post a Comment