AlgoMaster Logo

Move Zeroes

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force: Move and Shift

Intuition:

The simplest way to solve this problem is:

  1. Create a new array of the same size.
  2. Make a first pass over the original array:
    • Whenever you see a non-zero element, copy it into the next available position in the new array.
  3. After you’ve copied all non-zero elements, the front part of the new array will contain all non-zero numbers in their original order.
  4. Make a second pass on the new array (or just continue from where you stopped) and fill the remaining positions with 0.
  5. Finally, copy the new array back into the original one.

Code:

Example Walkthrough:

Input:

0
0
1
1
2
0
3
3
4
12
nums

After the first pass (collect non-zeroes into result):

0
1
1
3
2
12
3
0
4
0
result

The second pass fills the remaining positions with zero (they may already be zero, but that’s fine):

0
1
1
3
2
12
3
0
4
0
result

Finally, we copy result back into nums:

0
1
1
3
2
12
3
0
4
0
nums

2. Two-Pointers: Two Pass

Intuition:

A more efficient approach to solve this problem is using the two-pointer technique.

Use two indices:

  • writePos points to the next position to place a non-zero.
  • i scans the array.

First pass: copy every non-zero to nums[writePos] and advance writePos.

Second pass: fill the remaining positions with zeros.

This preserves the relative order of non-zeros.

Code:

Example Walkthrough:

Input:

0
0
1
1
2
0
3
3
4
12
nums

After first pass:

0
1
1
3
2
12
3
3
4
12
nums

After second pass:

0
1
1
3
2
12
3
0
4
0
nums

3. Two-Pointers: One-Pass

Intuition:

We can fine-tune our previous two-pointer approach by swapping in place.

Maintain two indices:

  • writePos points to the next position where a non-zero should live.
  • readPos scans the array left to right.

Whenever nums[readPos] is non-zero, swap it with nums[writePos] (only if readPos != writePos) and advance writePos. This compacts non-zeros in a single pass and leaves zeros behind naturally.

Code:

Example Walkthrough:

0
writePos
0
readPos
1
1
2
0
3
3
4
12
Step 1 / 6