Given an array of integers, move every 0 to the end while keeping the relative order of the non-zero elements the same, all done in place.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array of integers, move every 0 to the end while keeping the relative order of the non-zero elements the same, all done in place.
The simplest possible introduction to the write-pointer idea: a second index that only advances when something worth keeping is found, letting you compact an array in one pass without extra memory.
Whenever a problem asks you to remove or relocate certain values in place while preserving the relative order of everything else, look for a slow write pointer that trails a fast read pointer.
Maintain a write pointer that starts at index 0 and always marks where the next non-zero value belongs. Scan the array once with a read pointer: whenever the read pointer lands on a non-zero value, swap it into the write pointer's slot and advance the write pointer. Because the write pointer never advances past a slot that's already correctly filled, and every non-zero value is visited exactly once in order, this preserves their relative order automatically — swapping (rather than plain overwriting) also guarantees the displaced value is always a 0, so the zeros end up correctly pushed to the tail without a second pass.
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++;
}
}
}
}