Skip to main content

Move Zeroes

Problem Statement

Given an array of integers, move all zeroes to the end while maintaining the relative order of the non-zero elements. Modify the array in-place.

Function Signature:

function moveZeroes(arr) {
// Your code here
}

Examples

InputOutput
[0, 1, 0, 3, 12][1, 3, 12, 0, 0]
[0, 0, 1][1, 0, 0]
[1, 2, 3][1, 2, 3]
[0][0]

Constraints

  • Array length: 0 ≤ arr.length ≤ 10,000
  • Element values: -10⁹ ≤ arr[i] ≤ 10⁹

Interactive Editor

function moveZeroes(arr) {
// Your code here

}
Tests: 6 total

Hints

Hint 1: Similar to Remove Element

This is like "Remove Element" but instead of removing zeroes, you shift all non-zero elements forward, then fill the rest with zeroes.

Solution

View Solution Explanation
function moveZeroes(arr) {
let writeIndex = 0;

for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) {
arr[writeIndex] = arr[i];
writeIndex++;
}
}

while (writeIndex < arr.length) {
arr[writeIndex] = 0;
writeIndex++;
}

return arr;
}

First pass: move all non-zero elements to the front. Second pass: fill remaining positions with zeroes.

Complexity: O(n) time, O(1) space.