Move Zeroes
Given an integer array nums, move all 0s to the end while maintaining the relative order of non-zero elements. Do it in-place.
Example 1
Input: [0,1,0,3,12] → Output: [1,3,12,0,0]
Example 2
Input: [0] → Output: [0]
Solution Approach
Slow pointer tracks the position for the next non-zero element. Fast pointer scans all elements. When fast pointer finds a non-zero, swap with slow pointer and advance both.
- slow=0 (insertion point for non-zeros).
- For fast from 0 to n-1: if nums[fast]!=0, swap nums[slow] and nums[fast], slow++.
Java
class Solution {
public void moveZeroes(int[] nums) {
int slow = 0;
for (int fast = 0; fast < nums.length; fast++) {
if (nums[fast] != 0) {
int tmp = nums[slow]; nums[slow] = nums[fast]; nums[fast] = tmp;
slow++;
}
}
}
}
- Time Complexity: O(N)
- Space Complexity: O(1)