Move Zeroes in Java (Stable In-Place)
This guide explains the intuition, optimized approach, and Java implementation for move zeroes in java (stable in-place), with practical tips for interviews and production coding standards.
Problem
Move all 0s to end while preserving non-zero order.
Approach
Use write index insertPos for next non-zero value.
- Copy non-zero values forward.
- Fill remaining positions with zero.
Java Solution
class Solution {
public void moveZeroes(int[] nums) {
int insertPos = 0;
for (int n : nums) {
if (n != 0) {
nums[insertPos++] = n;
}
}
while (insertPos < nums.length) {
nums[insertPos++] = 0;
}
}
}
Complexity
- Time:
O(n) - Space:
O(1)
Key Takeaways
- Start from the brute-force idea, then derive the optimized invariant.
- Use clean pointer/index boundaries to avoid off-by-one bugs.
- Validate against edge cases (empty input, single element, duplicates, extreme values).