DSA and coding Level 1 This level · 17 of 19
Easy dsa two-pointers

Move Zeroes

The 30 second answer

I keep a write index for the next non-zero position and scan from the left. Whenever I see a non-zero I swap it into the write index and advance that index, so the non-zero values keep their order and the zeros bubble to the end. One pass, constant extra space.

Could you say this in an interview?

Problem Move all zeros in an integer array to the end, while keeping the relative order of the non-zero values. Do it in place. Original: LeetCode 283: Move Zeroes.

Understanding the prompt Order of the non-zero values matters. You may not copy the array. Swapping is allowed, and you do not have to minimise the number of writes.

Pattern recognition A read pointer and a write pointer moving in the same direction: the write pointer is the boundary of the compacted prefix.

Brute force Build a new array of the non-zero values, then pad zeros: O(n) space.

Optimal w is the next index that should hold a non-zero. For each r, if nums[r] is not zero, swap it with nums[w] and increment w. Zeros land on the right because every swap pulls a zero (or a value already processed) toward the end.

Alternatives Two passes: write every non-zero to the front, then fill the tail with zeros. That can do fewer swaps when most values are zero, but it is still O(n).

Java solution

import java.util.Arrays;

public class MoveZeroes {
    static void moveZeroes(int[] nums) {
        int w = 0;
        for (int r = 0; r < nums.length; r++) {
            if (nums[r] != 0) {
                int tmp = nums[w];
                nums[w] = nums[r];
                nums[r] = tmp;
                w++;
            }
        }
    }

    public static void main(String[] args) {
        var a = new int[] {0, 1, 0, 3, 12};
        moveZeroes(a);
        System.out.println(Arrays.toString(a)); // [1, 3, 12, 0, 0]
        var b = new int[] {0};
        moveZeroes(b);
        System.out.println(Arrays.toString(b)); // [0]
        var c = new int[] {1, 2, 3};
        moveZeroes(c);
        System.out.println(Arrays.toString(c)); // [1, 2, 3]
    }
}

Complexity O(n) time, O(1) extra space.

Edge cases

  • All zeros, or no zeros, both leave the array in a correct state.
  • A single element.
  • Zeros already at the end, which the swap should leave alone (w and r meet on a non-zero).

Follow-ups

  • Remove Duplicates from Sorted Array is the same write-pointer idea, keeping unique values instead of non-zeros.
  • Move some other sentinel, or keep at most k zeros.

Tests [0,1,0,3,12] becomes [1,3,12,0,0]. [0] stays [0]. [1,2,3] stays [1,2,3].

How to say it in the interview "I keep a write index for the next non-zero. I scan once, and whenever I see a non-zero I swap it into that index and advance the write pointer. The relative order stays the same and the zeros end up on the right. One pass, constant space."

Sources (1)
  1. LeetCode 283: Move Zeroesleetcode.com
Previous
Next