Approach 1Optimal▶ Animated
Write non-zeroes, then fill zeros
w is the next free slot. Copy every non-zero forward, then zero out the tail.
Relative order of non-zeroes is preserved because we copy them in the order we see them.
Algorithm
- Scan left to right; write each non-zero at
wand incrementw. - Fill
nums[w:]with zeros.
- Time
- O(n)
- Space
- O(1)
class Solution: def moveZeroes(self, nums: list[int]) -> list[int]: w = 0 for x in nums: if x != 0: nums[w] = x w += 1 for i in range(w, len(nums)): nums[i] = 0 return nums