Example 1
ready- Input
nums = [ 0, 1, 0, 3, 12 ]- Expected
[ 1, 3, 12, 0, 0 ]- Why
- the non-zero values keep their order, then two zeroes fill the tail
An activity feed has real event IDs mixed with empty slots marked 0. You want the
real events packed at the front without scrambling their order.
Given an integer array nums, move every zero to the end and return the resulting
array. The non-zero values must be stable, meaning they appear in the same relative
order as they did in the input.
A few ground rules:
nums.1 <= nums.length <= 100_000-2_147_483_648 <= nums[i] <= 2_147_483_647Hints
Collect the non-zero values in order, count how many slots remain, then append that many zeroes. What extra storage does that copy cost?
Keep a write index for the next non-zero value. Scan from left to right; whenever
you meet a non-zero value, place it at nums[write] and advance write.
Once every survivor has moved forward, all positions from write onward should be
zero. Filling that suffix finishes the array without another allocation.
Can you preserve the order while using O(1) extra space, even when almost every value is zero?
Visible cases
nums = [
0,
1,
0,
3,
12
][
1,
3,
12,
0,
0
]nums = [
0,
0,
0,
0
][
0,
0,
0,
0
]nums = [
4,
-2,
9
][
4,
-2,
9
]Interview signal
The direct version writes the rule almost word for word: collect every non-zero value, then add exactly enough zeroes to restore the original length.
def move_zeroes(nums: list[int]) -> list[int]:
non_zero = [value for value in nums if value != 0]
zero_count = len(nums) - len(non_zero)
return non_zero + [0] * zero_countBecause that list is built from left to right, it preserves the order automatically.
Time O(n) — every value is inspected once. Space O(n) — the returned construction holds a copy of the non-zero values and the padded zeroes.
The extra list isn't carrying new information. A write pointer can mark the next slot
that belongs to a non-zero value. Each survivor moves into that slot, in scan order, so
the compacted prefix is always correct.
After the scan, write is also the number of non-zero values. Every remaining position
belongs to the zero suffix.
def move_zeroes(nums: list[int]) -> list[int]:
write = 0
for value in nums:
if value != 0:
nums[write] = value
write += 1
for i in range(write, len(nums)):
nums[i] = 0
return numsWriting only at or behind the current read position is safe: you never overwrite a value that the scan hasn't seen yet. And because survivors are written in their original scan order, stability comes for free.
Time O(n) — the scan and suffix fill together touch at most 2n positions. Space O(1) — all work happens inside the returned array.
LeetCode's version mutates the array in place and returns void; ours returns the resulting array so the judge can compare it.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
[ 1, 3, 12, 0, 0 ]