Dutch National Flag - Problem
Given an array containing only 0s, 1s, and 2s, sort the array in-place in a single pass without using any sorting algorithm or counting sort.
The array represents the colors of the Dutch national flag: 0 represents red, 1 represents white, and 2 represents blue.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Constraints:
- The array contains only integers
0,1, and2 - You must solve this in one pass through the array
- Use constant extra space
Input & Output
Example 1 — Mixed Colors
$
Input:
nums = [2,0,2,1,1,0]
›
Output:
[0,0,1,1,2,2]
💡 Note:
All 0s (red) come first, then 1s (white), then 2s (blue). The Dutch flag pattern is achieved in one pass.
Example 2 — Already Sorted
$
Input:
nums = [0,1,2]
›
Output:
[0,1,2]
💡 Note:
Array is already in Dutch flag order, algorithm recognizes this and maintains the sorting.
Example 3 — Reverse Order
$
Input:
nums = [2,1,0]
›
Output:
[0,1,2]
💡 Note:
Worst case: completely reverse order gets sorted to proper Dutch flag sequence.
Constraints
- 1 ≤ nums.length ≤ 300
- nums[i] is either 0, 1, or 2
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code