Given an array of integers, move all 0s to the end while keeping the relative order of the non-zero elements. Do it in place.
Before you code
Removing each zero and appending it at the end shifts the rest of the array every time: O(n²). Instead, think of it as compacting the non-zero elements to the front and filling what is left with zeros.
Hints
- Keep a write index that starts at 0. Walk the array with a read index.
- Each time the read index finds a non-zero, copy it to the write index and advance the write index.
- After the pass, fill every slot from the write index to the end with 0.
- Variant: swap
nums[read]withnums[write]instead of copying, and the zeros end up at the back without a second loop.
Production & complexity notes
When solving Move zeroes on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Inserting and deleting in the middle to reinforce the underlying pattern.
What it practices
Removing many elements in one pass instead of one shift at a time, from Inserting and deleting in the middle.