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 with input: nums = [0,1,0,3,12]
The 1 stays first among non-zero values, and both zeroes move to the end.
Example with input: nums = [2,1]
Algorithm Flow
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.
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
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;
}
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
