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.

class Solution { public void sortColors(int[] nums) { int count0 = 0, count1 = 0, count2 = 0; for (int num : nums) { if (num == 0) count0++; else if (num == 1) count1++; else count2++; } for (int i = 0; i < nums.length; i++) { if (i < count0) nums[i] = 0; else if (i < count0 + count1) nums[i] = 1; else nums[i] = 2; } } }

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.

class Solution { public void sortColors(int[] nums) { int low = 0, mid = 0, high = nums.length - 1; while (mid <= high) { switch (nums[mid]) { case 0: int temp0 = nums[low]; nums[low] = nums[mid]; nums[mid] = temp0; low++; mid++; break; case 1: mid++; break; case 2: int temp2 = nums[mid]; nums[mid] = nums[high]; nums[high] = temp2; high--; break; } } } }

⚠️ Common Pitfalls

  • Forgetting that 2s go to the end and we don’t increment mid after swapping with high

  • 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

Popular posts from this blog

Deep Copy, Deep Dive – Clone That Graph!

Subarray Scores: Less Than K Challenge

Pascal's Triangle