Write a function that moves all zeroes to the end of an array while keeping the order of the other elements.
Use a write pointer: copy every non-zero value forward to the write position, then fill the remaining slots with zeroes. One pass, no extra array.
Explain it simply
Picture a queue at a railway ticket counter where some people are only holding a place for someone else (the zeroes). You walk down the line and ask each real passenger to step forward into the earliest free spot. When you reach the end, everyone who is left over is a placeholder and stands at the back.
Two pointers do this: read scans every element, and write marks the next spot for a non-zero value.
Example
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) {
nums[write] = nums[read];
write++;
}
}
while (write < nums.length) {
nums[write] = 0;
write++;
}
return nums;
}
console.log(moveZeroes([0, 1, 0, 3, 12])); // Output: [1,3,12,0,0]
console.log(moveZeroes([0, 0, 5])); // Output: [5,0,0]Complexity
Time O(n), space O(1).
What to say in the interview
"I would use two pointers. The read pointer walks the whole array, and the write pointer tracks where the next non-zero value belongs. After the scan I fill the rest with zeroes. It is in place, keeps the relative order, and runs in O(n) time with O(1) extra space."
Common mistakes
- Sorting the array to push zeroes back: that is O(n log n) and breaks the original order of the other numbers.
- Creating a new array when the question asks for an in-place change.