Skip to problem
←

Move Zeroes

Easy 0 attempts

Given an integer array nums, shift every 0 to the end of the array while keeping the non-zero elements in their original relative order. The operation must be performed in-place, without allocating a separate copy of the array.

Keep the array length and every value’s multiplicity unchanged. Negative values are nonzero and retain their place relative to other nonzero values. For [0,-2,0,1,-2], the result is [-2,1,-2,0,0]. Return nothing.

Function contract

Implement moveZeroes(nums). Receive a nonempty integer array and modify that same array.

Output: Leave all nonzero values in their original relative order, followed by all zeros. Preserve array length. Return nothing; the runner checks nums and ignores the return value.

Example 1

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

Example 2

Input
nums = [0,0]
Output
[0,0]
Constraints
  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

Use two pointers. A slow pointer tracks the position for the next non-zero element, while a fast pointer scans through the array. Swap non-zero elements forward to maintain relative order.

javascript
function moveZeroes(nums) {
  let slow = 0;

  for (let fast = 0; fast < nums.length; fast++) {
    if (nums[fast] !== 0) {
      [nums[slow], nums[fast]] = [nums[fast], nums[slow]];
      slow++;
    }
  }
}

Time: O(n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript