Skip to content
JsDevLife
Menu
  • Home
  • Leetcode in JS
  • About me
  • Contact Us
Menu

How to solve leetcode move zeroes problem in javascript

Posted on December 16, 2022July 30, 2023 by Vikas Kad

A Simple Solution in JavaScript to the LeetCode ‘Move Zeroes’ Problem

 

Problem statement

Given an integer array nums, move all 0’s to the end of it while maintaining the relative order of the non-zero
elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]

 

Example 2:

Input: nums = [0]

Output: [0]

 

Constraints:

1 <= nums.length <= 104

-231 <= nums[i] <= 231 – 1

 

Solution

One approach to solve this problem is to use two pointers. We can initialize a pointer left to the start of the
array and a pointer right to the end of the array. Then, we can iterate through the array with a third pointer i.
If the element at index i is non-zero, we can swap it with the element at index left, and increment left. If the
element at index i is zero, we can skip it and increment i. Once i reaches right, we can break the loop.
Here is the implementation in JavaScript:
function moveZeroes(nums) {

 

    let left = 0;

 

    let right = nums.length – 1;

 

 

    for (let i = 0; i <= right; i++) {

 

        if (nums[i] !== 0) {

 

            [nums[i], nums[left]] = [nums[left], nums[i]];

 

            left++;

 

        }

 

    }

 

 

    return nums;

 

}

 

This solution has a time complexity of O(n) and a space complexity of O(1), as it only uses constant extra space.

Test

We can test the function with the following code:
console.log(moveZeroes([0,1,0,3,12])); // [1,3,12,0,0]

 

console.log(moveZeroes([1,2,3,4,5])); // [1,2,3,4,5]

 

console.log(moveZeroes([0,0,0,0,1])); // [1,0,0,0,0]

 

console.log(moveZeroes([1,0,0,0,0])); // [1,0,0,0,0]

 

I hope this helps! Let me know if you have any questions.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Solving LeetCode Problem 79 – Word Search in JavaScript
  • Solving LeetCode Problem 48: Rotate Image using JavaScript
  • Solving the “Container With Most Water” LeetCode Problem in JavaScript – A Comprehensive Guide
  • LeetCode Solution: 54: Spiral Matrix in JavaScript
  • Solution to LeetCode Problem 31. Next Permutation in JavaScript

Archives

  • 2023 (5)
  • 2022 (20)
  • 2021 (2)
  • 2020 (4)
  • 2019 (14)
  • 2018 (17)

Categories

  • blockchain development
  • Blog
  • crystal
  • flutter
  • flutter.io
  • GitHub
  • Installation
  • Ionic Framework
  • javascript
  • leetcode-in-js
  • masteringInJavasript
  • mcqs
  • MongoDB
  • nodejs
  • Object Oriented Javacript
  • python
  • smart contracts
  • visual studio

Quick Links

  • Home
  • Leetcode in JS
  • About me
  • Contact Us

Terms of service

  • Terms Of Service
  • Disclaimer
©2023 JsDevLife | Design: Newspaperly WordPress Theme