Skip to the solution
EasyDSA10 min read

How do you move all zeroes to the end of an array in place?

691 views

The problem

Question presented to candidate: "Given a list of integers, move all the zeros to the end while keeping the order of the non-zero numbers, and do it in place, without making a copy of the list. Please write it in Python."

What a strong answer should cover:

  • Read/write two pointers: read scans every element, write marks the next slot for a non-zero; swap (or copy) non-zeros forward.
  • The invariant (non-zeros in order before write, zeros between write and read) and why it guarantees order is kept.
  • O(n) time, O(1) extra space; why remove plus append is O(nยฒ) and a filtered copy is O(n) space.
  • The two in-place variants (swap forward versus overwrite then fill) and their write counts.
  • Python specifics: in place means mutating the list object, so nums = [...] inside the function does nothing for the caller, while nums[:] = ... does (but builds a temporary list); the function returns None by convention.

Clarifying questions expected:

  • "Must the order of non-zero values be kept?"
  • "Is a temporary copy allowed, or must it be O(1) extra space?"

Code / implementation expected: Yes โ€” move_zeroes(nums) in Python with read and write indices, mutating the list and returning nothing.

  • arrays
  • 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

10 min read ยท 10 sections

Python code

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

PythonMove zeroes with read/write pointers on edge cases
PythonSwap forward vs overwrite then fill: counting writes

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 19 of 154 in DSA

Keep your momentum going.

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

All DSA questions
Up nextEasy

How do you check for valid/balanced parentheses?

Continue