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
Sort Colors: In-Place Sorting of 0s, 1s, and 2sInput Array:202110Dutch National Flag AlgorithmOutput Array:0011220s (Red)1s (White)2s (Blue)
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
Asked in
Microsoft 45 Amazon 38 Apple 32 Facebook 28
650.0K Views
High Frequency
~15 min Avg. Time
8.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen