Code Logo

Move Zeroes

Published at05 Jan 2026
1D Array Easy 52 views
Like18

This problem is about cleaning up the array without changing the order of the important numbers. In Move Zeroes, you want every 0 to end up at the back while all the non-zero values stay in the same relative order.

That detail matters a lot. You are not sorting the array, and you are not allowed to shuffle the non-zero values however you want. You only want to push the zeroes to the end and keep everything else lined up the same way as before.

For example, if the input is nums = [0,1,0,3,12], the answer is [1,3,12,0,0]. The non-zero values 1, 3, and 12 stay in the same order, and both zeroes move to the back. Another example is nums = [0,0,1], which gives [1,0,0]. The 1 moves forward, and the zeroes slide behind it.

So the goal is to rearrange the same array so that every non-zero value stays in order at the front, and every zero is moved to the remaining positions at the end.

Example Input & Output

Example 1
Input
nums = [0,1,0,3,12]
Output
[1,3,12,0,0]
Explanation

Example with input: nums = [0,1,0,3,12]

Example 2
Input
nums = [0,0,1]
Output
[1,0,0]
Explanation

The 1 stays first among non-zero values, and both zeroes move to the end.

Example 3
Input
nums = [2,1]
Output
[2,1]
Explanation

Example with input: nums = [2,1]

Algorithm Flow

Recommendation Algorithm Flow for Move Zeroes

Solution Approach

Move all zeroes to the end of an array while preserving non-zero relative order. Use a pointer pos tracking where the next non-zero should go. Iterate through the array; when a non-zero is found, place it at pos and advance pos. Fill remaining positions with zeroes.

function moveZeroes(nums) {
  var pos = 0;
  for (var i = 0; i < nums.length; i++) {
    if (nums[i] !== 0) { nums[pos] = nums[i]; pos++; }
  }
  for (var i = pos; i < nums.length; i++) nums[i] = 0;
}

The first pass compacts non-zero elements to the front. The second pass fills the tail with zeroes. This is in-place with O(1) extra space.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
import java.util.*;
class Solution {
    public void move_zeroes(int[] nums) {
        int write = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[write++] = nums[i];
            }
        }
        while (write < nums.length) {
            nums[write++] = 0;
        }
    }
}