Move Zeroes
Core idea: Walk one read pointer across the array; keep a write pointer just behind it marking the next open slot โ every value worth keeping gets pushed down into that slot, and whatever is left over becomes filler.
Problem, rephrased
Imagine you run a small online order queue. Each slot in the queue holds either a live order (any non-zero ticket number) or a cancelled placeholder (a 0). Over the day, cancellations pile up scattered throughout the queue. Before the next shift you want to slide every live order forward, keeping their original arrival order, and sweep all the cancelled placeholders to the tail โ and you must do it in the same physical array, because the queue is a fixed memory buffer you're not allowed to reallocate.
Formally: given an integer array nums, move every 0 to the end while keeping the relative order of the non-zero elements. Modify the array in place โ no returning a fresh list.
Input (nums) |
Output | Why |
|---|---|---|
[0, 9, 0, 4, 7] |
[9, 4, 7, 0, 0] |
Live orders 9,4,7 keep order; two 0s sink. |
[6, 0, 0, 8] |
[6, 8, 0, 0] |
6 and 8 stay ordered, zeros trail. |
[0, 0, 0] |
[0, 0, 0] |
Nothing live โ array unchanged. |
[2, 5, 1] |
[2, 5, 1] |
No zeros โ array unchanged. |
[-3, 0, -1, 0, 5] |
[-3, -1, 5, 0, 0] |
Negatives are "live"; only 0 is special. |
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson