Sort Colors
Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. The function should return the same array.
Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. The function should return the same array.
Statement
Given an array, colors, which contains a combination of the following three elements:
0(representing red)1(representing white)2(representing blue)
Sort the array in place so that the elements of the same color are adjacent, with the colors in the order of red, white, and blue. The function should return the same array.
Note: The function should only return the modified
colorsarray.
Constraints
- 1 ≤
colors.length≤ 300 colors[i]can only contain0s,1s, or2s.
Examples
Example 1
Input: colors = [2, 0, 2, 1, 1, 0]
Output: [0, 0, 1, 1, 2, 2]
Example 2
Input: colors = [2, 0, 1]
Output: [0, 1, 2]
Solution
We'll care three pointer low, mide and high , our primary focus will be on mid we'll check comparison with mid and swap accordingly , One edge case need to be keept in mide while solving this whenever mid receives 2 and we swap it with high we do not increment the value of low because we are not sure what value we got from high.
function sortColors(arr) {
let low = 0; // boundary for 0s
let mid = 0; // current element being examined
let high = arr.length - 1; // boundary for 2s
while (mid <= high) {
if (arr[mid] === 0) {
[arr[low], arr[mid]] = [arr[mid], arr[low]];
low++;
mid++;
} else if (arr[mid] === 1) {
mid++;
} else { // arr[mid] === 2
[arr[mid], arr[high]] = [arr[high], arr[mid]];
high--;
// note: mid is NOT incremented here
}
}
return arr;
}
console.log(sortColors([2, 0, 2, 1, 1, 0])); // [0, 0, 1, 1, 2, 2]