Move Zeroes
Push every 0 to the end of an array in place, keeping the other numbers in their original order.
The problem
You get an integer array nums. Move every 0 to the end of the array while keeping the non-zero numbers in their original relative order. Do it in place, without making a copy of the array; the function returns nothing.
Input nums = [0, 4, 0, 9, 2]
Output [4, 9, 2, 0, 0]
4, 9 and 2 keep their order, and both zeros end up at the back.
Input nums = [7, 0, -3]
Output [7, -3, 0]
Only the -3 has to move forward, past the single 0.
Key constraint: Work in place with O(1) extra space, and keep the non-zero numbers in order.
How to spot the pattern
- You must rearrange an array in place while keeping some items in their original order.
- One pointer can read every element while a second pointer marks where the next kept element belongs.
The idea
Keep a write pointer write that marks where the next non-zero number belongs. Scan the array with a read pointer; each time you meet a non-zero number, swap it into position write and move write forward. The non-zero numbers keep their order because they are placed in the order you meet them, and the zeros get pushed into the slots behind them.
Brute force: Copy the non-zero numbers into a new array and pad it with zeros, which is O(n) time but needs O(n) extra space and isn't in place.
Step by step
- 1Set
write = 0. - 2Scan the array with an index
readfrom left to right. - 3When
nums[read]is not 0, swapnums[read]withnums[write]and add 1 towrite. - 4When the scan ends, the non-zero numbers fill the front in their old order and the zeros fill the rest.
See the pattern move
The two pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
write = 0 # where the next non-zero number belongs
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1Complexity
Time
O(n)
Space
O(1)
One pass; each element is read once and swapped at most once.
Watch out for
- Deleting zeros from the middle one by one (with
remove,eraseorsplice), which shifts the rest of the array every time and costs O(n^2). - Building a new list and assigning it with
nums = ...in Python: that only rebinds the local name, and the caller's array stays unchanged.
Follow-up questions
Can you cut down the number of writes?
Skip the swap when read == write, which happens for every element before the first 0. Another version copies each non-zero number forward and fills the tail with zeros at the end; it writes each slot once and does no swaps.
What if you must remove every copy of a given value and return the new length?
Use the same read and write pointers: copy each element that is not the value to nums[write], and return write at the end. That is Remove Element.
In Hinglish
Ek pointer padhta hai, doosra likhne ki jagah yaad rakhta hai; har non-zero ko aage swap karo, zeros apne aap peeche chale jaayenge.