Back to DSA
Move Zeroes
easyGiven an integer array, rearrange it so that every zero appears at the end while all non-zero elements retain their original relative ordering. The transformation must be performed in-place, without creating a separate copy of the data.
Examples
Example 1:
Input:
arr = [0,4,0,2,7]Output:
[4,2,7,0,0]Explanation: Non-zero values 4, 2, and 7 keep their left-to-right order; zeroes are pushed to the back.
Example 2:
Input:
arr = [3]Output:
[3]Explanation: A single non-zero element requires no changes.
Hints
class Solution {
public void moveZeroes(int[] nums) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != 0) {
int temp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = temp;
slow++;
}
}
}
}Time complexity
O(n)Space complexity
O(1)