0:00 / 0:00

Push every zero to the end without changing the order of the rest, in place. A write pointer marks where the next non-zero belongs; swap each non-zero into it as you scan, and the zeros drift back in one O(n) pass with O(1) space.

▼

The problem

LeetCode 283 (Easy). Given an integer array nums, move all the 0s to the end while keeping the relative order of the non-zero elements, in place (without making a copy of the array).

Example (LeetCode's, the walkthrough): [0,1,0,3,12] → [1,3,12,0,0]; and [0] → [0].

TRY IT ON LEETCODE ▶

The solution

def moveZeroes(nums):
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:
            nums[write], nums[read] = nums[read], nums[write]
            write += 1

Transcript

Move Zeroes. You get a list of numbers. Move every zero to the end. The other numbers must keep their order, and you have to work in place, without making a second list.

Take zero, one, zero, three, twelve. The answer is one, three, twelve, zero, zero. One still comes before three, and three before twelve. A list with a single zero just stays as it is.

The easy way copies the non-zero numbers into a new list and pads it with zeros. It works, but extra space isn't allowed. To stay in place, you could bubble each zero toward the back, one swap at a time. That's correct too, but a long list can take n squared swaps.

Two pointers do it in one pass. Think of the list as a dragon boat, with rowers filling it from the front. A write pointer marks the first seat that still needs a rower. A read pointer walks down the boat and looks at every seat. When read finds a rower, the rower swaps into the write seat, and write moves up one. When read finds an empty seat, it just walks on. Every seat between write and read is empty, so the empty seats drift to the back.

In code: write starts at zero. Loop read over every index. If the number at read isn't zero, swap it with the number at write, then add one to write. That's the whole function.

Let's row our example. Read sees a zero: skip it. Read sees one: it swaps into seat zero, and write moves to one. Another zero: skip. Three swaps into seat one, and write moves to two. Twelve swaps into seat two, and write moves to three. The boat reads one, three, twelve, zero, zero.

Each number is read once, so the time is linear. Two indexes are all we keep, so the space is constant. And rowers are written in the order read finds them, so their order never changes.

Mark the write seat, scan, swap forward. That's Move Zeroes.