Skip to the solution
EasyDSAAsked in 20246 min read

Move Zeroes to End

3.3k views

The problem

Problem, as an interviewer would state it: "Implement moveZeroes(arr) — moving every 0 in the array to the END, while preserving the relative order of all non-zero elements, mutating the array IN PLACE (no new array allocated)."

Examples:

Code
moveZeroes([0,1,0,3,12]); // [1,3,12,0,0]

Clarifying questions expected:

  • Does this genuinely need to mutate the array IN PLACE, or would returning a new array be acceptable?
  • Should the RELATIVE order of the non-zero elements be preserved (a stable operation), or is any final order of non-zero elements acceptable?
  • Should a genuinely negative zero (-0) be treated the same as a plain 0?

Code / implementation expected: Yes — real, direct proof of in-place mutation (via a same-reference check), plus confirmation the relative order of non-zero elements is genuinely, stably preserved.

  • array
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: moveZeroes() genuinely mutates in place (same array reference) while stably preserving the relative order of non-zero elements

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 3 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Sync State Across Tabs Using the storage Event

Continue