Move Zeroes

EasyArrays · Two Pointers🧩 Array ManipulationLeetCode #283 ↗Updated

Problem

Given an integer array nums, move every 0 to the end while keeping the relative order of the non-zero elements. Do it in-place (no copy of the array).
Input[0,1,0,3,12]Output[1,3,12,0,0]
Input[0]Output[0]

1 ≤ n ≤ 104  ·  -231 ≤ nums[i] ≤ 231-1  ·  Follow-up: minimise total operations.

Try it yourself

Java
class Solution {
    public void moveZeroes(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Flip the problem: don't “move zeros back” — pack non-zeros to the front, in order. Whatever is left over must be zeros.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceExtra Array (Copy & Fill)

Time O(n)Space O(n)

Copy every non-zero into a new array result in order, fill the remaining slots with 0, then copy result back into nums.

Java
public void moveZeroes(int[] nums) {
    int n = nums.length;
    int[] result = new int[n];
    int j = 0;
    // First pass: accumulate non-zero elements
    for (int i = 0; i < n; i++) {
        if (nums[i] != 0) {
            result[j] = nums[i];
            j++;
        }
    }
    // Second pass: fill remaining positions with zeroes
    for (; j < n; j++) {
        result[j] = 0;
    }
    // Copy back to original array
    System.arraycopy(result, 0, nums, 0, n);
}

Easy to reason about, but uses O(n) extra memory and breaks the in-place rule.

At a glance

LevelApproachTimeSpace
Brute ForceExtra Array (Copy & Fill)O(n)O(n)
BetterTwo Pointers — Overwrite, then FillO(n)O(1)
OptimalTwo Pointers — Single-Pass SwapO(n)O(1)
Common pitfalls
  • Swapping when nums[i] == 0 — moves zeros forward.
  • Forgetting the fill loop (Better) — leaves stale values like [1,3,12,3,12].
  • Left/right swaps or sorting — destroys the relative order of non-zeros.
Interview tips
  • Start with the extra-array idea, then point out it breaks the in-place rule.
  • State the invariant: everything left of z is non-zero and in order.
  • Raise the follow-up yourself: the swap version minimises writes.
Pattern
Read/write (fast–slow) pointers → filter or compact an array in-place while keeping order.
My notes saved in this browser