Two Pointers — Move Zeroes
↗ LeetCode: Move Zeroes · Easy · pattern chapter →
Asked atMetaAmazonGoogleMicrosoftApple
Move all zeros to end preserving order of non-zeros. In-place.
Example 1 — nums=[0,1,0,3,12] → [1,3,12,0,0]Example 2 — nums=[0] → [0]
Constraints — 1 ≤ n ≤ 10⁴. Naive "build fresh array + copy back" is O(n) time but O(n) auxiliary memory — allocates twice, triggers GC pressure that costs ~5 min under stress. Two-pointer in-place stays O(n) = ~10⁶ pointer ops with O(1) extra space.
Progressive Hints
Try to solve it yourself first. Reveal hints only when stuck — each hint is progressively more specific.
Interview timer00:00
Practice under interview pressure. Start when you begin reading; stop when you finish. Save best only when you had a full working solution.
Target for interview: Medium = 20-25 min · Hard = 30-40 min · Best time persists on this device only.
Approach 1 — Two-pass write
Copy non-zeros forward; zero-fill tail.
Approach 2 — Slow/fast write pointer (canonical)
Insight. One pointer for read, one for the next slot to write.
java
void moveZeroes(int[] nums) {
int w = 0;
for (int r = 0; r < nums.length; r++)
if (nums[r] != 0) nums[w++] = nums[r];
while (w < nums.length) nums[w++] = 0;
}Execution Trace
Step 1 / 3Initialize scan.
Approach 3 — Swap on the fly (fewer writes)
Use when array is mostly zeros — each non-zero causes one swap.
java
void moveZeroesSwap(int[] nums) {
int w = 0;
for (int r = 0; r < nums.length; r++)
if (nums[r] != 0) { int t = nums[r]; nums[r] = nums[w]; nums[w++] = t; }
}Complexity — Time O(n); Space O(1).
Try it yourself
Complexity summary
| Approach | Time | Space | Grade |
|---|---|---|---|
| Two-pass | O(n) | O(1) | baseline |
| Slow/fast writer | O(n) | O(1) | canonical |
| Swap-in-place | O(n) | O(1) | fewer writes |
When to use which
- Standard → slow/fast.
- Minimize writes (SSD wear, etc.) → swap variant.
- Removes / partition → same template family.
AI Study CompanionBeta
Related problems
Was this page helpful?
📚 Related problems