Overview
Given an array nums containing only 0, 1, and 2, sort it in-place so that objects of the same color are adjacent (0s, then 1s, then 2s). Do not use the library sort function.
This is the Dutch National Flag problem.
Constraints
1 <= nums.length <= 300nums[i]is 0, 1, or 2.- One-pass with O(1) extra space.
Examples
sortColors([2,0,2,1,1,0]); // => [0,0,1,1,2,2] sortColors([2,0,1]); // => [0,1,2]
Solution
Reveal solution
function sortColors(nums) {
let lo = 0, mid = 0, hi = nums.length - 1;
while (mid <= hi) {
if (nums[mid] === 0) { [nums[lo], nums[mid]] = [nums[mid], nums[lo]]; lo++; mid++; }
else if (nums[mid] === 1) mid++;
else { [nums[mid], nums[hi]] = [nums[hi], nums[mid]]; hi--; }
}
return nums;
}Resources
sort-colors.js
Sort Colors
mediumcodingAlgorithmsTwo Pointers
Overview
Given an array nums containing only 0, 1, and 2, sort it in-place so that objects of the same color are adjacent (0s, then 1s, then 2s). Do not use the library sort function.
This is the Dutch National Flag problem.
Constraints
1 <= nums.length <= 300nums[i]is 0, 1, or 2.- One-pass with O(1) extra space.
Examples
sortColors([2,0,2,1,1,0]); // => [0,0,1,1,2,2] sortColors([2,0,1]); // => [0,1,2]
Solution
Reveal solution
function sortColors(nums) {
let lo = 0, mid = 0, hi = nums.length - 1;
while (mid <= hi) {
if (nums[mid] === 0) { [nums[lo], nums[mid]] = [nums[mid], nums[lo]]; lo++; mid++; }
else if (nums[mid] === 1) mid++;
else { [nums[mid], nums[hi]] = [nums[hi], nums[mid]]; hi--; }
}
return nums;
}Resources
NameTopicDifficulty
103 of 103 problems