84. Move Zeroes
easyAsked at RedditMove zeros to the end while keeping the order of non-zeros. Reddit uses this to test in-place two-pointer technique — the same compact-and-tombstone pattern used when removing soft-deleted comments from a tree without rebuilding it.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Reddit loops.
- Glassdoor (2026-Q1)— Reddit phone-screen warm-up.
Problem
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.
Constraints
1 <= nums.length <= 10^4-2^31 <= nums[i] <= 2^31 - 1
Examples
Example 1
nums = [0,1,0,3,12][1,3,12,0,0]Example 2
nums = [0][0]Approaches
1. Compact + fill zeros
First pass: copy non-zeros forward. Second pass: fill remaining with 0.
- Time
- O(n)
- Space
- O(1)
function moveZeroes(nums) {
let k = 0;
for (const n of nums) if (n !== 0) nums[k++] = n;
while (k < nums.length) nums[k++] = 0;
}Tradeoff: Two passes. Most writes.
2. Two-pointer swap (optimal)
Slow points to next zero position; fast scans. On nonzero, swap with slow and advance slow.
- Time
- O(n)
- Space
- O(1)
function moveZeroes(nums) {
let slow = 0;
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== 0) {
[nums[slow], nums[fast]] = [nums[fast], nums[slow]];
slow++;
}
}
}Tradeoff: Single pass with minimum writes when zeros are rare.
Reddit-specific tips
Reddit interviewers want the two-pointer swap. Bonus signal: connect to soft-deleted comments — same compact-with-tombstone shape.
Common mistakes
- Swapping when nums[fast] === 0 (does nothing useful and wastes work).
- Forgetting to advance slow only on swap.
- Using extra space when in-place is required.
Follow-up questions
An interviewer at Reddit may pivot to one of these next:
- Remove element (LC 27).
- Move all negatives to front.
- Sort colors (LC 75).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
When does this minimize writes?
When zeros are rare. Each non-zero hop costs one swap; the leading prefix has many same-position swaps (no-ops) but no useless writes.
Why not skip swap when slow == fast?
Tiny optimization. The swap is a no-op anyway.
Practice these live with InterviewChamp.AI
Drill Move Zeroes and other Reddit interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →