DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 283. Move Zeroes

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.log(nums)
};
Enter fullscreen mode Exit fullscreen mode

Using Two Pointer Approach

The left pointer is initialized to 0. This pointer indicates where the next non-zero element should be placed.

The right pointer iterates through each element of the array nums.

If the current element (nums[right]) is not zero, it means it needs to be moved to the position indicated by the left pointer.

Swap the element at the left pointer with the element at the right pointer. This places the non-zero element in its correct position (i.e., at the left pointer's position) and moves any previous non-zero element further to the right if needed.

After placing a non-zero element at the left pointer's position, increment left to point to the next position where the next non-zero element should be placed.

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    let left = 0
    for(let right = 0; right < nums.length; right++){
        if(nums[right] !== 0){
            [nums[left], nums[right]] = [nums[right], nums[left]]        
            left++
        }

    }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)