DEV Community

Urfan Guliyev
Urfan Guliyev

Posted on • Edited on

Leetcode - Move Zeros (with JavaScript)

Today I am going to show how to solve the Move Zeros algorithm problem.

Here is the problem:
Alt Text

There are multiple ways to solve this problem. Brute Force is the first method everybody comes up with. We iterate through the given array, push all non-zero elements to the newly created array, and then fill the rest of it with 0’s.

But as noted in the problem, we should solve this in-place without making a copy of the array. That’s why I am using the two pointer approach.

1) First, I declare variable nonZeroIndex to keep track of where (index) I am going to place the variable if it is not 0.



var moveZeroes = function(nums) {
    let nonZeroIndex = 0;
};


Enter fullscreen mode Exit fullscreen mode

2) I walk through the array by using the “for” loop to check whether or not an element is 0. As we keep finding new non-0 elements, we just overwrite them at the "nonZeroIndex + 1" 'th index.



var moveZeroes = function(nums) {

    let nonZeroIndex = 0;

    for(let i=0; i < nums.length; i++){
        if(nums[i] != 0) {
            nums[nonZeroIndex] = nums[i];
            nonZeroIndex ++;
        }
    }
};


Enter fullscreen mode Exit fullscreen mode

3) Once we’ve reached the end of the array, we see that all of the non-zero elements have been moved to the beginning of the array in their original order. We now need to move all of the 0's to the end. We do this by simply filling the rest of the array (all the indexes after the "nonZeroIndex" index) with 0’s.



var moveZeroes = function(nums) {

    let nonZeroIndex = 0;

    for(let i=0; i < nums.length; i++){
        if(nums[i] != 0) {
            nums[nonZeroIndex] = nums[i];
            nonZeroIndex ++;
        }
    }

    for(let i = nonZeroIndex; i < nums.length; i++) {
        nums[i] = 0;
    }

};


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
kamo profile image
KAIDI

Loop
If zero found slice it then push it at the end
for( const n of arr)
If n==0
arr.slice(n)
arr.push(0)

Collapse
 
felipevillajr profile image
Felipe Villa • Edited

what if one of the values in the array was a boolean. how would you adjust for that