mediumJS ES5#106

Ceros al final (move zeros)

Prompt

Move all zeros in an array to the end while preserving the order of other elements. Return a new array; do not mutate the input.

Solution

function moveZeros(arr) {
  return arr.filter(x => x !== 0).concat(arr.filter(x => x === 0))
}
Mentor's take

This is a stable partition: split elements into two groups by a predicate while preserving relative order within each group. The two-filter idiom — non-zeros concatenated with zeros — expresses that directly. Two passes over the array plus a concat: O(n) time, O(n) space, no mutation of the input.

The naive approach interviewers are fishing for is splice inside a loop: find a zero, remove it, push it to the end. That's O(n²) — every splice shifts the remaining elements — and it mutates the array you're iterating, which skips elements when two zeros are adjacent. It's a two-bug answer.

The in-place alternative worth naming is the two-pointer write-index technique from LeetCode's "Move Zeroes": walk the array, write each non-zero at a write pointer, then fill the tail with zeros. That's O(n) time, O(1) extra space — better if mutation is allowed. The filter version trades a little memory for immutability and readability; in React-adjacent code, returning a new array is usually the requirement, not a cost.

One strictness note: filter with x !== 0 — a truthiness check like filter(Boolean) would also evict false, '', and null.

Red flag: splice while iterating — O(n²) plus index-skipping — or a truthiness filter that deletes falsy non-zeros.

Say it: "It's a stable partition: two filters and a concat, O(n) and immutable — and if in-place O(1) space were required, I'd switch to a write-pointer sweep."