283. Move Zeroes
Quick Identifier
- Topic: two-pointers
- Pattern: stable overwrite pointer
- Difficulty: Easy
- Companies: Amazon, Facebook, Bloomberg, Apple, Adobe
- Frequency: High
- LeetCode: 283
- Hint:
writeis the next position for a non-zero.readscans every value once.
Quick Sights
- Time Complexity:
O(n)- one read pass plus zero fill. - Space Complexity:
O(1)- in-place mutation. - Core Mechanism: Copy non-zero values forward with
write, then fill the remaining suffix with zeroes.
Concept Explanation
This is a stable partition. Non-zero values must keep their relative order, and zeroes move behind them.
The invariant is: everything before write is the final non-zero prefix. The read pointer scans the original data. Every non-zero is promoted to write; zeroes are ignored until the suffix fill.
Diagram
This diagram shows the pointer decisions and the step-by-step algorithm flow.
Loading diagram…
Study Pattern (SDE3+)
- 0-3 min: Name the pointer shape, then state the invariant and discard rule before coding.
- Implementation pass: Keep pointer movement explicit; every branch must return, record an answer, or move at least one pointer.
- 5 min extension: Explain how the solution changes for immutable input, streaming input, many duplicate values, or many repeated queries.
Approaches
- Extra array is easy but
O(n)space. Swapping works too. Stable overwrite plus zero fill is easy to explain and constant space.
Optimal Solution
JavaScript
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) nums[write++] = nums[read];
}
while (write < nums.length) nums[write++] = 0;
}Go
func moveZeroes(nums []int) {
write := 0
for read := 0; read < len(nums); read++ {
if nums[read] != 0 {
nums[write] = nums[read]
write++
}
}
for write < len(nums) {
nums[write] = 0
write++
}
}Walkthrough
[0,1,0,3,12] writes non-zero prefix [1,3,12], then fills two zeroes: [1,3,12,0,0].
Edge Cases
- All zeroes
- No zeroes
- One element.
Pitfalls
- Breaking relative order
- Forgetting zero fill
- Returning a new array.
Similar Problems
Mind-Map Tags
#two-pointers #stable-partition #overwrite
Mark this page when you finish learning it.
Last updated on
Spotted something unclear or wrong on this page?