DSA interview question
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].
void moveZeroes(vector<int>& a); // in place; non-zero elements keep their relative order
Input a | Output | Explanation |
|---|---|---|
[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in