I am trying to solve a problem in O(n) without taking space (like map of object).I want to shift all zeros in beginning , one's in last and two's in middle.
input : [0, 1, 0, 2, 1] Expected output : [0,0,2,1,1] here is my code
let arr = [0, 1, 0, 2, 1];
function swap(input, i, j) {
let temp = input[i];
input[j] = input[i];
input[i] = temp;
}
function moveZeroOneAndTwo(input) {
let i = 0,
j = input.length - 1;
while (i < j) {
while (arr[i] !== 0) i++;
while (arr[j] !== 0) j--;
swap(arr, j, i);
i++;
j--;
}
return input
}
console.log(moveZeroOneAndTwo(arr))
I am trying to find 1 index from left and zero index from right and swap them still not able to solve this question