Sort Colors - Problem
๐จ Sort Colors (Dutch National Flag Problem)
You're organizing a collection of colored objects that need to be arranged in a specific order! Given an array nums with n objects colored red, white, or blue, your task is to sort them in-place so that objects of the same color are grouped together.
The Challenge:
- Objects are represented by integers:
0= red,1= white,2= blue - Final arrangement must be: red โ white โ blue
- Sort in-place (modify the original array)
- No built-in sort functions allowed!
Example: [2,0,2,1,1,0] becomes [0,0,1,1,2,2]
This classic problem is also known as the Dutch National Flag Problem, named after the three colors of the Netherlands flag! ๐ณ๐ฑ
Input & Output
example_1.py โ Basic Case
$
Input:
[2,0,2,1,1,0]
โบ
Output:
[0,0,1,1,2,2]
๐ก Note:
The array contains 2 red objects (0), 2 white objects (1), and 2 blue objects (2). After sorting in-place, all reds come first, then whites, then blues.
example_2.py โ Already Sorted
$
Input:
[0,1,2]
โบ
Output:
[0,1,2]
๐ก Note:
The array is already sorted with red, white, and blue in correct order. No changes needed.
example_3.py โ Single Color
$
Input:
[1,1,1]
โบ
Output:
[1,1,1]
๐ก Note:
All objects are the same color (white), so the array remains unchanged after sorting.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Zones
Create three zones with boundaries: red zone, processing zone, blue zone
2
Process Each Ball
Examine current ball: if red, send to red zone; if white, keep in middle; if blue, send to blue zone
3
Adjust Boundaries
After each placement, update zone boundaries to reflect new organization
4
Complete Sorting
When processing zone is empty, all balls are perfectly organized!
Key Takeaway
๐ฏ Key Insight: The Dutch National Flag algorithm maintains three distinct regions simultaneously, allowing us to sort in a single pass by intelligently moving boundaries as we process each element. This transforms a potentially complex sorting problem into an elegant three-way partitioning solution!
Time & Space Complexity
Time Complexity
O(nยฒ)
In worst case, we need O(n) passes and each pass takes O(n) time to scan the array
โ Quadratic Growth
Space Complexity
O(1)
Only uses a constant amount of extra space for loop variables and swapping
โ Linear Space
Constraints
- n == nums.length
- 1 โค n โค 300
- nums[i] is either 0, 1, or 2
- You must solve this problem without using the library's sort function
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code