#283
Move Zeroes
Easy Read/write pointers
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Move all zeros to the end of the array in place, keeping the order of the non-zero elements.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: push zeros to the end, keep the other numbers in order.
Why this works: swap every non-zero to the next write position. Zeros drift right automatically.
Example: [0, 1, 0, 3, 12]
1 → swap with index 0 → [1, 0, 0, 3, 12]3 → swap with index 1 → [1, 3, 0, 0, 12]12 → swap with index 2 → [1, 3, 12, 0, 0]
✦Hints open one at a time
First compact the non-zero values to the front.
Or swap each non-zero element with the first zero position as you go.
↗Approach
Keep write = position for the next non-zero. When you see a non-zero at read, swap it with nums[write] and advance write. Zeros drift to the end and the non-zero order is kept.
</>Solution (Java)
class Solution {
public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int t = nums[write];
nums[write++] = nums[read];
nums[read] = t;
}
}
}
}
!Common mistake
Swapping zeros toward the end with bubble-like passes — O(n²).
Complexity
- Time: O(n).
- Space: O(1).
