DEV Community

Masaki Fukunishi
Masaki Fukunishi

Posted on

LeetCode #283 Move Zeroes with JavaScript

Solution to LeetCode's 283. Move Zeroes with JavaScript.

Solution

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
const moveZeroes = (nums) => {
  for (let i = nums.length - 1; i >= 0; i--) {
    if (nums[i] === 0) {
      nums.splice(i, 1);
      nums.push(0);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Time complexity: O(n)
  • Space complexity: O(1)

It is important to process from the back of the array, since 0 is added to the end of the array.

Top comments (0)