AlgoViz

Move Zeroes

Easy

In-place · keep non-zeros in order

In simple words

Keep one finger on the next empty spot and slide every non-zero forward, so the zeros pile up at the back.

The idea

A slow pointer marks where the next non-zero belongs; a fast pointer scans ahead. Whenever fast finds a non-zero, drop it into the slow slot. Zeros naturally pile up at the end.

slow
fast
0
1
0
3
12
0
1
2
3
4

Step 1 of 7. "slow" marks where the next non-zero belongs. "fast" scans the whole array. Values: 0, 1, 0, 3, 12. Pointers: slow at index 0, fast at index 0.

1/7
Optimal
timeO(n)spaceO(1)

Compact non-zeros forward.

1// slow marks the next non-zero slot2let slow = 0;3for (let fast = 0; fast < n; fast++) {4  if (nums[fast] === 0) continue;5  [nums[slow], nums[fast]] = [nums[fast], nums[slow]];6  slow++;7}8// zeros have rolled to the end

Input

array
[0, 1, 0, 3, 12]

Memory

slow
= 0 [0]
fast
= 0 [0]

Output

result

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
nums = [0, 1, 0, 3, 12]
Output:
[1, 3, 12, 0, 0]
Explanation:
Non-zeros keep order, zeros slide to the back.

Example 2

Input:
nums = [0, 0, 1]
Output:
[1, 0, 0]
Explanation:
The single 1 moves to the front.

Example 3

Input:
nums = [1, 2, 3]
Output:
[1, 2, 3]
Explanation:
No zeros, so nothing moves.

Finished the walkthrough? Add it to your streak.