LeetCode #283 Easy

Move Zeroes

Move Zeroes is LeetCode 283 (Easy). Given an integer array nums, move every 0 to the end of the array.

  • The non-zero values must keep their original relative order.
  • The change must happen in place: no copy of the array.

The follow-up asks to keep the number of writes to the array as low as possible.

Constraints
  • 1 <= nums.length <= 10⁴
  • -2³¹ <= nums[i] <= 2³¹ - 1
arraytwo-pointersin-place
Open on LeetCode ↗
02

Intuition

Think of the array as two zones: a finished front part holding the non-zero values seen so far, and everything after it. A write pointer marks where the front part ends, and a read pointer scans every slot once.

  • Read finds a zero: skip it. It already belongs further back.
  • Read finds a non-zero: swap it into the slot at write, then move write forward.

Every slot between write and read holds a zero, so each swap sends a zero backward and pulls a non-zero value forward. Values reach the front in the order they are read, which is why their order survives.

How to spot this pattern

Rearrange an array in place so that values passing a test come first, in order: that is the read/write pointer pattern. Remove Element and Remove Duplicates from Sorted Array use the same two pointers, keeping a different kind of value.

03

Approach

Try it first

Before reading on, decide what the slots between the two pointers always contain. Aim for one pass, O(1) extra space, and no writes when the array has no zeros.

1

Start both pointers at the front

Set write = 0. Nothing is in its final place yet, so the first non-zero value should land in slot 0.

2

Scan with read and skip zeros

Move read from left to right over every slot. A zero is left where it is for now; write stays put, so it keeps pointing at the first zero that has to be pushed back.

3

Swap each non-zero value forward

When nums[read] is not zero, swap it with nums[write] and add 1 to write. If no zero has been seen yet, the two pointers are equal and the swap leaves the array unchanged.

4

Why the order is kept

Non-zero values are placed at write one at a time in reading order, and a value never moves again once placed. So the front holds them exactly as they appeared, and only zeros are left behind.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def moveZeroes(self, nums):
▶3 write = 0
▶4 for read in range(len(nums)):
▶5 if nums[read] != 0:
▶6 nums[write], nums[read] = nums[read], nums[write]
▶7 write += 1
writeread▼00110233124write starts at slot 0
write0
nums[0, 1, 0, 3, 12]
write marks the next slot that should hold a non-zero number. Nothing has been placed yet, so it starts at slot 0.
writeread▼▼00110233124slot 0 is 0 → skip it, write stays at 0
read0
write0
A zero belongs at the back, so nothing happens. write stays at slot 0, which now holds a zero waiting to be swapped out by the next non-zero number.
writeread▼▼10010233124swap 1 into slot 0, the 0 goes to slot 1
read1
write0
nums[1, 0, 0, 3, 12]
1 is not zero, so it goes to slot 0. That slot held a zero (everything between write and read is zero), so the swap sends that zero back to slot 1. Non-zero numbers arrive at write in the order they were read, which keeps their order.
writeread▼▼10010233124slot 2 is 0 → skip it, write stays at 1
read2
write1
A zero belongs at the back, so nothing happens. write stays at slot 1, which now holds a zero waiting to be swapped out by the next non-zero number.
writeread▼▼10310203124swap 3 into slot 1, the 0 goes to slot 3
read3
write1
nums[1, 3, 0, 0, 12]
3 is not zero, so it goes to slot 1. That slot held a zero (everything between write and read is zero), so the swap sends that zero back to slot 3. Non-zero numbers arrive at write in the order they were read, which keeps their order.
writeread▼▼10311220304swap 12 into slot 2, the 0 goes to slot 4
read4
write2
nums[1, 3, 12, 0, 0]
12 is not zero, so it goes to slot 2. That slot held a zero (everything between write and read is zero), so the swap sends that zero back to slot 4. Non-zero numbers arrive at write in the order they were read, which keeps their order.
writeread10311220304done: 3 numbers kept in order, 2 zeros at the back
nums[1, 3, 12, 0, 0]
Every non-zero number was swapped into the front in reading order, so slots 0 to 2 hold them in their original order. Each zero was only ever pushed backward, so the rest are zeros.
05

Compact, then fill with zeros

The first loop copies each non-zero value to nums[write] and advances write, overwriting whatever was there; nothing is lost, because write never passes the value being read. When the loop ends, slots from write to the end must hold zeros, so a second loop writes them.

▶1class Solution:
▶2 def moveZeroes(self, nums):
▶3 write = 0
▶4 for x in nums:
▶5 if x != 0:
▶6 nums[write] = x
▶7 write += 1
▶8 for i in range(write, len(nums)):
▶9 nums[i] = 0
06

Common pitfalls

Swapping zeros with values from the far end

✗ Wrong
left, right = 0, len(nums) - 1
while left < right:
    if nums[left] == 0:
        nums[left], nums[right] = nums[right], nums[left]
        right -= 1
    else:
        left += 1
✓ Right
nums[write], nums[read] = nums[read], nums[write]

Pulling values in from the end puts zeros at the back but scrambles the order. [0, 1, 2] becomes [2, 1, 0], while the expected answer is [1, 2, 0].

07

Complexity

Time
O(n)
Space
O(1)
Each slot is read once and every swap is constant work. The only extra memory is the two indices.
08

Move Zeroes FAQ

Which version does fewer writes to the array?

The swap version writes only when it meets a non-zero value, two writes per swap, and none for zeros. The fill version below writes every slot once. Arrays with many zeros favour the swap; arrays with few zeros favour the fill. Skipping the swap when read == write cuts writes further when the array starts with non-zero values.

How do I move the zeros to the front instead?

Run the same idea from the right: start write at the last index, scan read leftward, and swap each non-zero value into write, moving write left. The non-zero values then keep their order at the back.