283. Move Zeroes
At a Glance
- Topic: two-pointers
- Pattern: Two Pointers
- Difficulty: Easy
- Companies: Amazon, Facebook, Bloomberg, Apple, Adobe
- Frequency: High
- LeetCode: 283
Problem (one-liner)
Given an integer array nums, move all 0s to the end while preserving the relative order of non-zero elements. Must be in-place.
Recognition Cues
- "Move zeros to end"
- "Preserve relative order of non-zeros"
- In-place array transformation
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force — build new array —
O(n)time /O(n)space — disallowed if in-place only. - Better — count non-zeros then second fill — two passes
O(n)/O(1). - Optimal — single pass write pointer —
O(n)time /O(1)space — swap or assign non-zeros forward.
Optimal Solution
Go
func moveZeroes(nums []int) {
write := 0
for read := 0; read < len(nums); read++ {
if nums[read] != 0 {
nums[write], nums[read] = nums[read], nums[write]
write++
}
}
}JavaScript
function moveZeroes(nums) {
let write = 0;
for (let read = 0; read < nums.length; read++) {
if (nums[read] !== 0) {
[nums[write], nums[read]] = [nums[read], nums[write]];
write++;
}
}
}Walkthrough
Input: nums = [0,1,0,3,12]
| read | write | action |
|---|---|---|
| 0 | 0 | skip 0 |
| 1 | 0 | swap 1 to front, write=1 |
| 2 | 1 | skip 0 |
Invariant: [0..write-1] has all non-zeros in original encounter order; zeros drift right via swaps.
Edge Cases
- No zeros
- All zeros
- Single element
Pitfalls
- Second loop filling zeros from
writeonward when using assign-only variant (here swap handles zeros implicitly)
Similar Problems
- 75. Sort Colors — multi-value partitioning.
- 27. Remove Element — same write-pointer pattern (if file exists; else use index naming).
- 125. Valid Palindrome — two indices discipline.
Variants
- Move zeros while counting swaps (minimum swap variant).
- Stable partition without swapping (copy twice) if extra buffer allowed.
Mind-Map Tags
#two-pointers #in-place #partition #stable-order #swap-write
Last updated on
Spotted something unclear or wrong on this page?