Move Zeroes Easy 0 attempts
LeetCode ↗

Move Zeroes

Easy ArrayTwo Pointers LeetCode

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.

Sample Input
nums = [0,1,0,3,12]
Sample Output
[1,3,12,0,0]
Constraints
  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
Test Cases
Case 1
Args: [[0,1,0,3,12]] Expected: [1,3,12,0,0]

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.

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)

Saved in this browser only. Private to you.

JavaScript