Move Zeroes

EASY

Description

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

 

Example 1:

Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]
Output: [0]

 

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

 

Follow up: Could you minimize the total number of operations done?

Approaches

Checkout 3 different approaches to solve Move Zeroes. Click on different approaches to view the approach and algorithm in detail.

Brute Force with Extra Array

Use an additional array to store non-zero elements first, then fill remaining positions with zeros.

Algorithm

  1. Create new array of same size as input
  2. Copy non-zero elements maintaining order
  3. Fill remaining positions with zeros
  4. Copy back to original array

This approach uses an extra array to solve the problem in two passes:

  1. Create a new array of the same size as input
  2. Iterate through the input array and copy non-zero elements to the new array
  3. Fill remaining positions with zeros
  4. Copy back elements to original array
public void moveZeroes(int[] nums) {
    int[] result = new int[nums.length];
    int nonZeroIndex = 0;
    
    // First pass: copy non-zero elements
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] != 0) {
            result[nonZeroIndex++] = nums[i];
        }
    }
    
    // Fill remaining positions with zeros
    while (nonZeroIndex < nums.length) {
        result[nonZeroIndex++] = 0;
    }
    
    // Copy back to original array
    for (int i = 0; i < nums.length; i++) {
        nums[i] = result[i];
    }
}

Complexity Analysis

Time Complexity: O(n) where n is the length of the array - requires two passes through the arraySpace Complexity: O(n) where n is the length of the array - requires extra array of same size

Pros and Cons

Pros:
  • Simple to understand and implement
  • Maintains relative order of non-zero elements
  • Only requires two passes through the array
Cons:
  • Uses extra space
  • Not in-place as required by the problem
  • Requires copying elements back to original array

Code Solutions

Checking out 4 solutions in different languages for Move Zeroes. Click on different languages to view the code.

class Solution { public void moveZeroes ( int [] nums ) { int i = - 1 , n = nums . length ; for ( int j = 0 ; j < n ; ++ j ) { if ( nums [ j ] != 0 ) { int t = nums [++ i ]; nums [ i ] = nums [ j ]; nums [ j ] = t ; } } } }

Video Solution

Watch the video walkthrough for Move Zeroes



Patterns:

Two Pointers

Data Structures:

Array

Companies:

Subscribe to Scale Engineer newsletter

Learn about System Design, Software Engineering, and interview experiences every week.

No spam, unsubscribe at any time.