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, and 2
  • 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
INPUTALGORITHMRESULTMixed Flag Colors ArrayDutch Flag 3-Pointer MethodSorted Flag Pattern202110nums = [2,0,2,1,1,0]1Initialize 3 pointers2low=0, mid=0, high=53Scan and partition:• 0 --> swap to low zone• 1 --> keep in middle• 2 --> swap to high zone4Continue until mid > high001122Red ZoneWhite ZoneBlue Zone[0,0,1,1,2,2]Perfect Dutch Flag!Key Insight:Three pointers maintain distinct zones (0s, unprocessed, 2s) enabling single-pass partitioning without counting or extra space.TutorialsPoint - Dutch National Flag | Three-Pointer Partitioning Algorithm
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 28
187.6K Views
High Frequency
~15 min Avg. Time
8.9K 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