These clues point to Two Pointers: Read and Write: A fast pointer reads every element and a slow pointer marks where the next kept element should be written.
Stuck? Take one hint at a time
Solution.java · starter
class Solution {
public void moveZeroes(int[] nums) {
int write = 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
write marks the next spot for a non-zero. When nums[read] is non-zero, swap it with nums[write] and advance write. Zeros naturally collect after write.
▶ Dry run: Swapping non-zeros to the frontnums = [0, 1, 0, 3, 12]
0
0
↑w↑r
1
1
0
2
3
3
12
4
Step 1/5nums[0] is 0: skip.
Approach 1
class Solution {
public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int tmp = nums[write];
nums[write] = nums[read];
nums[read] = tmp;
write++;
}
}
}
}
Verdict: One pass, order preserved.
Before you submit
Edge cases and common mistakes
Test these inputs
No zeros
All zeros
Zeros only at the end
Mistakes people make
Swapping zeros with the last element (breaks the order of non-zeros).