Algorithms

Move Zeroes

EasyLast updated: 02/05/2026, 16:00:00 PST
01

Problem Statement

Given an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array. Minimize the total number of operations.

  • All non-zero elements should appear in the same relative order as in the original array. All zeros should be at the end.
  • We can do a single pass with a "write" pointer: whenever we see a non-zero, place it at the write position and advance write. Then fill the rest with zeros (or swap to avoid a second pass).
02

Key Observations

  • Two pointers: write points to the next position where we should put a non-zero. We scan with read. When nums[read] != 0, we put it at write (swap with nums[write] or just assign nums[write] = nums[read]) and write++. After the scan, all non-zeros are in [0..write-1] in order; we can set nums[write..n-1] = 0 if we used assign instead of swap.
  • If we swap, we don't need a second loop: each non-zero is swapped to the front and the zero that was there (if any) goes to the current read position and will be processed later.
03

Approach

High-level: write = 0. For each index read: if nums[read] != 0, swap nums[write] and nums[read] (or assign nums[write]=nums[read] and later zero out the tail), then write++. All non-zeros end up in [0..write-1] in order.

Steps:

  1. write = 0. For read = 0..n-1: if nums[read] != 0, swap nums[write] and nums[read], write++.
  2. (Optional) For i = write..n-1, set nums[i] = 0 if we used assign instead of swap.
04

Implementation

Java
public void moveZeroes(int[] nums) {
    int write = 0;

    for (int read = 0; read < nums.length; read++) {
        if (nums[read] != 0) {
            if (read != write) {
                int t = nums[read];
                nums[read] = nums[write];
                nums[write] = t;
            }

            write++;
        }
    }
}
05

Test Cases

Example 1

Input
nums = [0,1,0,3,12]
Expected
[1,3,12,0,0]
Explanation
Zeros moved to end.
06

Complexity Analysis

  • Time: O(n).
  • Space: O(1).
07

Follow-ups

  • Move zeros to the front; move a specific value to end.