Algo-Sim › Two Pointers

Move Zeroes

Easy · Two Pointers · step through it in Java, Python and C++ on your own input

Move every 0 to the end in place, keeping the other values in their original order.

Problem

Given an integer array nums, move every 0 to the end of the array while keeping the non-zero values in their original relative order. Do it in place, without copying the array.

Constraints

Edge cases to test

Follow-up questions

How do you minimise the number of writes?
Swap each non-zero with the first zero slot instead of writing then filling zeros: writes only where values move.
Is the order of the non-zeros kept?
Yes: the slow pointer writes them in their original order, so the partition is stable, unlike a quicksort-style partition.

Solution

Java

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

Python

def move_zeroes(nums):
    write = 0
    for read in range(len(nums)):
        if nums[read] != 0:
            nums[write], nums[read] = nums[read], nums[write]
            write += 1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void moveZeroes(vector<int> &nums) {
        int write = 0;
        for (int read = 0; read < int(nums.size()); read++) {
            if (nums[read] != 0) {
                int tmp = nums[write];
                nums[write] = nums[read];
                nums[read] = tmp;
                write++;
            }
        }
    }
};

More Two Pointers problems