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:
readscans every element,writemarks the next slot for a non-zero; swap (or copy) non-zeros forward. - The invariant (non-zeros in order before
write, zeros betweenwriteandread) and why it guarantees order is kept. - O(n) time, O(1) extra space; why
removeplusappendis 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, whilenums[:] = ...does (but builds a temporary list); the function returnsNoneby 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.