shlogg · Early preview
Rakesh Reddy Peddamallu @rakesh678219

Two Pointer Approach To Move Zeroes In Array

Two approaches to move zeros in an array: Naive Approach with swapping and Two Pointer Approach. The latter is more efficient, incrementing the left pointer after placing a non-zero element at its position.

Naive Approach

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    //counting no of zeroes
    let n = nums.map((i)=> i==0).length;
    while(n>0){
        //after 1 loop , 1 zero will be moved to end
        for(let i = 0 ;i<nums.length-1;i++){
                let j = i+1
                if(nums[i]==0 ){
                    //swapping
                    let c = nums[i]
                    nums[i] = nums[j];
                    nums[j] = c
                }
            }
        n--;
    }
    console...