Skip to content

visual walkthrough

Move Zeroes

EasySame Direction (Read/Write)Reported at: MetaMicrosoftAmazon+7

Stable in-place partitioning with minimal writes.

Solve on LeetCode

The idea

Scan once with `read`. Each non-zero value is swapped into the slot at `write`, and `write` moves on. Zeros are never moved explicitly; they get pushed backwards by the swaps.

Non-zeros keep their original order, which is exactly what the problem asks for.

Complexity

approachtimespace
Copy to a new arrayO(n)O(n)
Swap forwardO(n)O(1)

More walkthroughs