Move ZeroesLoading saved progress…

Move Zeroes

moveZeroes rearranges an array so that every 0 sits at the end while the non-zero values keep their original relative order — and it does this in place, mutating the array you were given instead of building a new one. This is the classic LeetCode 283 interview problem, and the point is the in-place technique, not the result: you return the same array reference you were handed.

Signature

moveZeroes(nums)
// mutate `nums` in place — pushing the zeros to the end — then RETURN that same array

Examples

moveZeroes([0, 1, 0, 3, 12]); // → [1, 3, 12, 0, 0]
moveZeroes([0, 0, 1]);        // → [1, 0, 0]   leading zeros slide to the end
const a = [4, 0, 5];
moveZeroes(a) === a; // → true   the return value IS the same array, now mutated

Notes

  • In place — change the array you were given and return it; the returned array must be the same reference, so moveZeroes(a) === a is true. Do not allocate or return a new array.
  • Order is preserved — the non-zero elements keep their original relative order; only the zeros move.
  • Zeros bunch at the end — every 0 collects in one run at the tail, and the array's length never changes.
  • Only the literal 0 — a value counts as a zero only when it is === 0. Falsy-but-not-zero values like false, '', and null are non-zero and stay in place.
  • Edge cases — an empty array, a single element, an all-zero array, and an array whose zeros are already at the end all come back unchanged (still the same reference).

FAQ

Does moveZeroes create a new array or mutate the original?
It mutates the array in place and returns that same reference, so moveZeroes(a) === a is true. It does not allocate a new array, and the caller's variable sees the change.
What is the time and space complexity?
O(n) time — a single pass over the array — and O(1) extra space, since the non-zeros are packed in place with a write pointer and no second array is allocated.
Are falsy values like false, empty string, or null treated as zeroes?
No. Only the literal number 0 (matched with strict ===) is moved. Falsy-but-not-zero values such as false, the empty string, and null count as non-zero here and keep their positions.
Loading editor…