Two Pointers · In place

Move Zeroes Visualizer

What is Move Zeroes

Move every zero to the end and keep the order of the other values. Return the whole array. A write pointer marks the next slot for a non-zero. A read pointer scans the array once.

0 1 0 3 12
1 3 12 0 0

Approach

Build a new listCollect the non-zeros, then append the zeros. That uses extra memory and hides the swap that does the same job in place.
Swap non-zeros forwardWhenever the reader sees a non-zero, swap it with the write slot and advance the writer. Zeros drift to the end and the relative order stays.

Interactive solution

Read and write pointers, zeros drifting right
write = 0
for read in range(n):
if a[read] != 0: swap a[write], a[read]; write += 1
else: leave the zero
return a
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n)One pass of swaps.
MemoryO(1)The same array is rearranged.

Implementation

def move_zeroes(a):
    w = 0
    for r in range(len(a)):
        if a[r] != 0:
            a[w], a[r] = a[r], a[w]
            w += 1
    return a