Move Zeroes solution explained
To move all zeroes to the end of an array in place while keeping the other values in order, use two pointers: a fast pointer reads every element, and a slow write pointer marks where the next non-zero value goes. Copy each non-zero value forward to the write position, then fill the remaining slots with zeros, or swap instead of copying so the zeros travel back on their own. Both run in O(n) time and O(1) extra space.
By Evin JohnPublished 6 min read
Restating it
You receive an integer array. Rearrange it so that all zeros sit at the end, while the non-zero values keep the order they had. The change must happen in the array you were given, not in a copy you return. A frequent extra request is to keep the number of writes to the array low.
| Before | After |
|---|---|
| [0, 4, 0, 0, 9, 1] | [4, 9, 1, 0, 0, 0] |
| [7, 0, -2, 0] | [7, -2, 0, 0] |
| [3, 8] | [3, 8], unchanged |
| [0, 0] | [0, 0], unchanged |
What it is really testing
This is an easy question, so interviewers grade it on precision. Can you keep order stable, which rules out the simple swap-from-both-ends trick? Do you mutate in place rather than rebinding a variable? Can you explain the invariant of the two-pointer loop? It often opens a session, and a clean answer with a stated invariant sets a good tone for the harder question that follows.
Variations
- Order of non-zeros does not matter. Swap zeros from the front with non-zeros from the back, which can mean fewer writes but is not stable.
- Remove every copy of a given value and return the new length. The same write pointer, without the zero fill.
- Move zeros to the front instead. Run the write pointer from the right end toward the left.
- Minimize writes. The swap version only writes when a zero sits before the current value.
Baseline with a second list
Collect the non-zero values into a new list, pad it with as many zeros as were removed, and copy the result back into the original. In Python, slice assignment does the copy back and keeps the same list object, which is what in place requires. It is O(n) time and O(n) extra space.
def move_zeroes_with_copy(nums):
kept = [x for x in nums if x != 0]
nums[:] = kept + [0] * (len(nums) - len(kept))Writing nums = kept + zeros instead of nums[:] = ... would create a new local list and leave the caller's array untouched, a bug that passes in your head and fails in the judge.
Write pointer, then fill
Keep an index called write that starts at 0. Read the array from left to right. Every non-zero value is copied to position write, and write moves forward. Because write never passes the read position, nothing unread is overwritten. When the read is finished, everything from write to the end must be zeros, so set those positions to zero. The invariant is simple to state: positions before write hold the non-zero values seen so far, in their original order.
def move_zeroes(nums):
write = 0
for x in nums:
if x != 0:
nums[write] = x # pack non-zeros to the front, in order
write += 1
for i in range(write, len(nums)):
nums[i] = 0 # whatever is left is zerosSwap as you go, in JavaScript
The swap version folds the fill into the main loop. A slow pointer marks the first slot that may hold a zero. When the fast pointer finds a non-zero value, swap it into the slow position and advance slow. Zeros are pushed back one swap at a time and end up at the tail. The fast !== slow check skips pointless self-swaps when no zero has been seen yet, which keeps writes at zero for an array that has no zeros at all.
function moveZeroes(nums) {
let slow = 0; // first position that may hold a zero
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== 0) {
if (fast !== slow) {
[nums[slow], nums[fast]] = [nums[fast], nums[slow]];
}
slow++;
}
}
}Which version writes less depends on the data. The fill version writes each non-zero once and each zero once. The swap version writes two positions per swap but nothing at all before the first zero. If the interviewer cares, ask what the data usually looks like.
Complexity
| Approach | Time | Extra space | Stable |
|---|---|---|---|
| New list, copy back | O(n) | O(n) | Yes |
| Write pointer and fill | O(n) | O(1) | Yes |
| Swap as you go | O(n) | O(1) | Yes |
| Swap from both ends | O(n) | O(1) | No, non-zero order changes |
Edge cases
- No zeros: the array must be unchanged.
- Only zeros: also unchanged.
- Zeros only at the start, or only at the end.
- Negative values, which are non-zero and must keep their place in the order.
- An empty array, if the problem allows it.
Mistakes
- Rebinding the array name instead of changing its contents.
- Removing zeros with a delete-in-loop, which shifts the remaining items and makes the solution O(n²).
- Swapping zeros with values from the back, which breaks the order of the non-zero values.
- Forgetting the zero fill after the write-pointer loop.
- Treating negative numbers or false-like values as zero in a language with loose comparisons.
How to explain it
Fictional example
- Candidate
- I'll keep a write index. Everything before it is the non-zero values I've read so far, in order.
- Candidate
- I read left to right. A non-zero value goes to the write index and the index moves up. Since write never passes the reader, I never overwrite something I haven't read.
- Candidate
- At the end, every slot from write onward should be zero, so I fill them. One pass and a fill, constant extra space.
- Interviewer
- Could you avoid the second loop?
- Candidate
- Yes, swap instead of copy. The zeros get pushed back by the swaps, so the tail is already zeros when the loop ends.
Related problems
Sort Colors extends the same partition idea to three values. Rotate Array and 4Sum are further pointer exercises on arrays, and Majority Element is another single-pass, constant-space question. The full list has more.
Where Natively helps
Quick problems like Move Zeroes are good for drilling how you speak while you code. Natively transcribes a practice session on Mac or Windows, so you can reread whether you stated the invariant before typing. If you are stuck on a variation, it can read the problem from a screenshot and suggest an approach and code to compare with yours. Read about the AI interview assistant.
Questions people ask
How do you move zeroes to the end without extra space?
Use a write pointer. Copy each non-zero value to the write position and advance it, then set every position from the write pointer to the end to zero. It is O(n) time and O(1) space.
Does Move Zeroes need to keep the order of the other numbers?
Yes, in the standard version the non-zero values must keep their original order. That rules out swapping zeros with values taken from the back of the array.
What is the swap version of Move Zeroes?
A slow pointer marks the first slot that may hold a zero. Each non-zero value found by the fast pointer is swapped into that slot, so zeros drift to the end in one pass.
Why does my Move Zeroes solution not change the array?
You probably assigned a new list to the variable. Change the contents instead, for example with slice assignment in Python or by writing indices directly.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
