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 - Dutch National Flag Algorithm INPUT Array with colors (0=Red, 1=White, 2=Blue) 2 0 2 1 1 0 0 1 2 3 4 5 0 = Red 1 = White 2 = Blue Three Pointers: low=0, mid=0, high=5 Input Array: [2, 0, 2, 1, 1, 0] ALGORITHM STEPS 1 Initialize Pointers low=0, mid=0, high=n-1 2 If nums[mid] == 0 Swap(low, mid), low++, mid++ 3 If nums[mid] == 1 Just mid++ (correct position) 4 If nums[mid] == 2 Swap(mid, high), high-- Pointer Regions: 0..low-1 low..mid-1 high+1..n Continue while mid <= high Complexity: Time: O(n) - single pass Space: O(1) - in-place FINAL RESULT Sorted by color order 0 0 1 1 2 2 RED WHITE BLUE OK Sorted in-place! Execution Trace: [2,0,2,1,1,0] swap(0,5) [0,0,2,1,1,2] low++,mid++ [0,0,2,1,1,2] swap(2,4) [0,0,1,1,2,2] mid++ [0,0,1,1,2,2] Done! Key Insight: The Dutch National Flag algorithm uses three pointers (low, mid, high) to partition the array into three regions in a single pass. Elements before 'low' are 0s (red), between 'low' and 'mid' are 1s (white), and after 'high' are 2s (blue). TutorialsPoint - Sort Colors | Dutch National Flag (Optimal Solution)
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