Move Zeroes

Given an array of integers, move every 0 to the end while keeping the relative order of the non-zero elements the same, all done in place.

EasyMust DoTwo Pointers
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array of integers, move every 0 to the end while keeping the relative order of the non-zero elements the same, all done in place.

Why solve this?

The simplest possible introduction to the write-pointer idea: a second index that only advances when something worth keeping is found, letting you compact an array in one pass without extra memory.

Pattern Recognition

Whenever a problem asks you to remove or relocate certain values in place while preserving the relative order of everything else, look for a slow write pointer that trails a fast read pointer.

Prerequisites

  • Comfort with basic array traversal and in-place index writes.

Hints

  1. You don't need to know how many zeros there are in advance — you just need to know where the next non-zero value should be written.
  2. Keep a 'write' index that only moves forward when you place a non-zero value there.
  3. Swapping the read and write positions (instead of just overwriting) means the zeros end up in the freed slots automatically.

Approach

Maintain a write pointer that starts at index 0 and always marks where the next non-zero value belongs. Scan the array once with a read pointer: whenever the read pointer lands on a non-zero value, swap it into the write pointer's slot and advance the write pointer. Because the write pointer never advances past a slot that's already correctly filled, and every non-zero value is visited exactly once in order, this preserves their relative order automatically — swapping (rather than plain overwriting) also guarantees the displaced value is always a 0, so the zeros end up correctly pushed to the tail without a second pass.

Code

Solution.java
class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0;
        for (int fast = 0; fast < nums.length; fast++) {
            if (nums[fast] != 0) {
                int temp = nums[slow];
                nums[slow] = nums[fast];
                nums[fast] = temp;
                slow++;
            }
        }
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays