Sort colors (Dutch national flag)
Medium TimeO(n) SpaceO(1)
The array nums holds only 0s, 1s and 2s — red, white and blue, the Dutch national flag. Sort it in place and in a single pass, with no counting pass and no second array, so every 0 comes first, then the 1s, then the 2s. Equal values need no particular order among themselves.
Examples
Example 1
- Input
- nums = [2, 0, 2, 1, 1, 0]
- Output
- Two of each colour, gathered: the
[0,0,1,1,2,2]0s, then the1s, then the2s.
Example 2
- Input
- nums = [2, 0]
- Output
- One of each, and the pair is exchanged.
[0,2]
The Code
function sortColors(nums) {
let low = 0;
let mid = 0;
let high = nums.length - 1;
while (mid <= high) {
if (nums[mid] === 0) {
const t = nums[low];
nums[low] = nums[mid];
nums[mid] = t;
low++;
mid++;
} else if (nums[mid] === 1) {
mid++;
} else {
const t = nums[mid];
nums[mid] = nums[high];
nums[high] = t;
high--;
}
}
return nums;
}
sortColors([2, 0, 2, 1, 1, 0]);Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Reverse array Swap the ends and step inward until the pointers meet.
- Most water Widest gap first; always move the shorter wall inward.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Remove duplicates A fast reader and a slow writer compact the array in place.