banner
Koresamuel

Koresamuel

Sometimes ever, sometimes never.
github
twitter
email

283. Move Zeroes

Problem Description#

Given an array nums, write a function to move all 0's to the end of the array while maintaining the relative order of the non-zero elements.

Note: 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 <= 10^4
-2^31 <= nums[i] <= 2^31 - 1

Approach#

  1. The simplest approach is to traverse the array and whenever a 0 is encountered, move it to the end of the array. This approach requires creating a new array.
  2. We can use two pointers, one starting from the left and the other starting from the right. Whenever a 0 is encountered, it is moved to the end of the array and the right pointer is moved one step to the left. Otherwise, the left pointer is moved from left to right.

Solution#

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
  let l = 0, r = nums.length;
  while (l < r) {
    if (nums[l] === 0) {
      nums.push(nums.splice(l, 1));
      r--;
    } else {
      l++;
    }
  }
};

Move Zeroes

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.