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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay