PPractick

DSA interview question

Move Zeros to the End

Easy · Algorithms · Topics: array, two pointer

The problem

A sensor log stores one reading per second, with 0 meaning "no reading". The analytics team wants all real readings at the front in their original order, followed by all the zeros, so a downstream job can process the prefix without skipping blanks. It must be done in place. Removing each zero and appending it is O(n²) because of all the shifting. A two-pointer pass does it in O(n): one pointer scans, the other marks where the next non-zero value should go.

Example: [0, 1, 0, 3, 12] → [1, 3, 12, 0, 0].

Function signature

void moveZeroes(vector<int>& a);  // in place; non-zero elements keep their relative order

Test cases

Input aOutputExplanation
[0, 1, 0, 3, 12][1, 3, 12, 0, 0]Order of 1, 3, 12 preserved
[4, 0, 5, 0, 0, 6][4, 5, 6, 0, 0, 0]
[0, 0, 1][1, 0, 0]
[1, 2, 3][1, 2, 3]No zeros: unchanged
[0][0]
[][]

(Confirm: in place, O(1) extra space; the relative order of non-zero elements must not change.)

How interviewers phrase it

Clarifying questions to ask

  1. Must the non-zero elements keep their order? (That rules out simple swapping from both ends.)
  2. In place?
  3. Should I minimise the number of writes?

Follow-ups to expect

  1. "Why does swapping preserve order?"
  2. "Can you reduce writes?"
  3. "Why not two pointers from both ends?"
  4. "How is this related to partitioning in quick sort?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in