BudiBadu Logo

Move Zeroes

Array Easy 1 views
Like18

You are given an array of integers. Your goal is to move all the zeros in the array to the end, while keeping the relative order of the other (non-zero) elements unchanged. The modification should be done in-place, meaning you cannot create a copy of the array to achieve this.

This task challenges your ability to manipulate array positions carefully without disrupting the sequence of meaningful values. Consider the array as a line of numbered cards—each card should stay in the same order, but every “0” card needs to slide to the end. It’s essential to handle sequences of multiple zeros gracefully and ensure no non-zero number changes position relative to the others.

This type of problem emphasizes understanding data movement within arrays and efficient updates without creating extra memory structures. The operation should maintain the same array length and content (only rearranged). When there are no zeros, the array should remain unchanged. If all elements are zeros, it should stay the same.

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [2,1]
Output: [2,1]

Algorithm Flow

Recommendation Algorithm Flow for Move Zeroes - Budibadu
Recommendation Algorithm Flow for Move Zeroes - Budibadu

Best Answers

java
import java.util.*;
class Solution {
    public int[] move_zeroes(int[] nums) {
        int[] res = new int[nums.length];
        int idx = 0;
        for (int x : nums) if (x != 0) res[idx++] = x;
        return res;
    }
}