Sort Colors - Problem
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.
You must solve this problem without using the library's sort function.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,0,2,1,1,0]
›
Output:
[0,0,1,1,2,2]
💡 Note:
Sort the colors in-place: all 0s first, then 1s, then 2s
Example 2 — Already Sorted
$
Input:
nums = [0,1,2]
›
Output:
[0,1,2]
💡 Note:
Array is already sorted with one of each color
Example 3 — All Same Color
$
Input:
nums = [1,1,1]
›
Output:
[1,1,1]
💡 Note:
All elements are the same color, no changes needed
Constraints
- n == nums.length
- 1 ≤ n ≤ 300
- nums[i] is either 0, 1, or 2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with mixed colors [2,0,2,1,1,0]
2
Process
Use Dutch National Flag algorithm to partition
3
Output
Sorted array [0,0,1,1,2,2]
Key Takeaway
🎯 Key Insight: Use three pointers to partition the array in one pass, maintaining regions for each color
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code