Skip to content

Move Zeroes

LeetCode 283 · Easy

Move all zeroes to the end, keeping nonzero values in their original order. Modify the same array; do not return a new array.

Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Stable compaction: gather the values to keep at the front, in the order encountered. A read pointer scans the input; a write pointer marks the next available position.

The prefix before the write pointer contains exactly the nonzero values encountered so far. Reading left to right and advancing the write pointer only for nonzeros preserves order. Fill the remaining suffix with zeroes.

Implement: accepted version, as reported by the learner
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
zero_pointer = 0
l = 0
r = 0
for num in nums:
nums[l] = nums[r]
if num == 0:
r += 1
else:
l += 1
r += 1
for i in range(l, len(nums)):
nums[i] = 0

The unconditional copy works: a zero copied to l is temporary, and a later nonzero overwrites it. The write position never overtakes the read position. zero_pointer is unused, and r is redundant because num already contains nums[r].

Implement: simpler equivalent
class Solution:
def moveZeroes(self, nums: list[int]) -> None:
write = 0
for num in nums:
if num != 0:
nums[write] = num
write += 1
for i in range(write, len(nums)):
nums[i] = 0

Yes. Find the earliest zero and take the next nonzero to its right. The original idea was workable; swapping itself does not imply loss of relative order.

Animation input: [0, 1, 0, 3, 12]. Expected output: [1, 3, 12, 0, 0]. Orange marks the earliest zero; blue marks the next nonzero.

Animation showing stable forward swaps

Step Action Array
1 Swap indexes 0 and 1 [1, 0, 0, 3, 12]
2 Swap indexes 1 and 3 [1, 3, 0, 0, 12]
3 Swap indexes 2 and 4 [1, 3, 12, 0, 0]

The nonzeros enter the prefix as 1, then 3, then 12. Taking 12 from the end first would jump ahead of 1 and 3, breaking stability.

Static frames for revision

All forward-swap animation frames

The submitted scan plus zero-fill takes O(n) time and O(1) auxiliary space.

A nested-while variant can also be O(n) if both pointers only advance. Repeatedly restarting a search can cost more. Always check bounds before accessing an index.

Explain why writing while iterating is safe here. What would go wrong if the write pointer moved ahead of the read pointer? Which swap partner preserves nonzero order?

Study record: acceptance was self-reported. The pasted implementation was reviewed by inspection. The original while-loop version was described verbally, so its exact code and complexity were not verified.