Skip to content
BytePatterns

Move Zeroes

Arrays: lesson 6 of 8

Push the junk to the back without losing the order.

Lesson 6 of 8 · 5 min

Move Zeroes

Step 1 of 13

write marks the next slot that should hold a non-zero. read scans everything.

The Idea

Keep a write pointer for the next slot that should hold a non-zero value. Scan with a read pointer and copy every non-zero forward. Then pad the tail with zeros: one pass, no second array, order preserved.

Real-World Example

A theatre compacts a half-empty row before the show starts. Ushers slide the seated guests forward in the same order they arrived, leaving every empty seat gathered at the aisle end.

The Code

def move_zeroes(nums):
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:
            nums[write] = nums[read]   # keeps relative order
            write += 1
    while write < len(nums):
        nums[write] = 0                # pad the tail
        write += 1
    return nums

print(move_zeroes([0, 4, 0, 9, 2]))   # [4, 9, 2, 0, 0]

Your turn

Put the steps in the right order.

  1. Fill the remaining slots with zeros
  2. Set the write pointer to 0
  3. Copy each non-zero value into the write slot
  4. Scan the array with a read pointer

Mini quiz

1 / 3

What does the write pointer track?