Steps to get the solution:
1) Count the number of 0's using 'for' loop and store it in a variable e.g zeroCount.
2) Now we know that remaining items will be 1's.
3) Run 'for' loop till zeroCount, and replace the array items with 0.
4) Run one more 'for' loop to fill the remaining items with 1.
Below is the code to segregate 0s and 1s in an array:
function arrangeNumber(arr) {
let zeroCount =0;
for(let i=0;i < arr.length;i++) {
if(arr[i]==0) {
zeroCount += 1;
}
}
for(let i=0;i < zeroCount;i++) {
arr[i] = 0;
}
for(let i=zeroCount;i < arr.length;i++) {
arr[i] = 1;
}
return arr;
}
const nums = [1,0,0,1,0,1,1];
const finalres= arrangeNumber(nums);
console.log('final result', finalres); // output : [0,0,0,1,1,1,1]
Time complexity and Space complexity:
Time complexity :- O(n) // as we dont have nested for loops
Space complexity: O(1) // as we are only storing values in variable and not storing anything in array etc