Move Zeroes

A fast reader scans; a slow writer marks where the next non-zero belongs. Swapping non-zeros forward pushes every zero to the end while preserving order.

Category
Two Pointers
Time complexity
O(n)
Space complexity
O(1)

Pseudocode

write ← 0
for each i
  if a[i] ≠ 0: swap into write, write++
zeros end up at the tail

Reference implementation

w = 0
for i in range(n):
    if a[i] != 0:
        a[w], a[i] = a[i], a[w]
        w += 1

Open the interactive Move Zeroes visualisation →