O(n) O(1)
Intuition
Use a slow pointer to track the position for the next non-zero element. Fast pointer scans through the array.
Explanation
Approach
- Slow pointer marks the position for the next non-zero.
- Fast pointer scans left to right.
- When fast finds a non-zero, swap with slow position and advance slow.
Complexity
- Time: O(n)
- Space: O(1)
Implementation
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++;
}
}
}
}