Move Zeroes

Pattern: Two pointers

easy

Move all zeros to the end in place, keeping the other values in order, with a read pointer and a write pointer.

The problem

You are given an array nums. Move every 0 to the end, keeping the other values in their original order. Do it in place, without making a copy of the array. For example, [0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0].

The function name moveZeroes matches LeetCode, where the function changes the array and returns nothing. Use the link above for the exact statement.

Think first

  • Where should the first non-zero value end up? The second?
  • If you keep a "next free slot" index for non-zero values, when does it move?
  • Why does swapping (rather than just copying) leave the zeros at the end automatically?

Hints

    Brute force, and why it fails

    Copy the non-zero values into a new array and fill the rest with zeros: O(n) time but O(n) extra memory, which the problem forbids. Bubbling each zero to the end with repeated neighbour swaps is in place but O(n²).

    The key insight

    write never gets ahead of read, so swapping nums[read] into slot write can only move a value forwards and a zero backwards. One pass with two indexes does the whole job in place.

    Dry run

    00read, write
    11 
    02 
    33 
    124 
    write0

    nums = [0, 1, 0, 3, 12]. write marks where the next non-zero value goes. It starts at 0.

    Step 1 of 6

    The plan

    write = 0
    for read from 0 to n - 1:
        if nums[read] != 0:
            swap nums[write] and nums[read]
            write = write + 1
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass, at most one swap per element, and two indexes.

    Edge cases

    • No zeros: every value swaps with itself, and nothing changes.
    • All zeros: nothing moves.
    • A single element: unchanged.
    I've built my logic, show the code

    Java

    class Solution {
        public void moveZeroes(int[] nums) {
            int write = 0;                          // next place for a non-zero value
            for (int read = 0; read < nums.length; read++) {
                if (nums[read] != 0) {
                    int temp = nums[write];
                    nums[write] = nums[read];
                    nums[read] = temp;
                    write++;
                }
            }
        }
    }

    C++

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int write = 0;                          // next place for a non-zero value
            for (int read = 0; read < static_cast<int>(nums.size()); read++) {
                if (nums[read] != 0) {
                    swap(nums[write], nums[read]);
                    write++;
                }
            }
        }
    };

    Python

    class Solution:
        def moveZeroes(self, nums: list[int]) -> None:
            write = 0                               # next place for a non-zero value
            for read in range(len(nums)):
                if nums[read] != 0:
                    nums[write], nums[read] = nums[read], nums[write]
                    write += 1

    Common mistakes

    • Removing zeros from a list while looping over it, which skips elements and costs O(n) per removal.
    • Copying non-zeros forward but forgetting to fill the tail with zeros.
    • Sorting, which does not keep the original order of the non-zero values.

    Similar problems