14. Move Zeroes
easyAsked at SnapMove all zeros in an array to the end while preserving relative order of non-zero elements. Snap uses this to test two-pointer in-place rearrangement.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Snap loops.
- LeetCode Discuss (2025)— Snap warm-up problem in onsite coding rounds.
- Glassdoor (2026-Q1)— Often used as the second array problem on Snap screens.
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. Two-pass copy
First pass copies non-zeros to the front; second pass fills the rest with zeros.
- Time
- O(n)
- Space
- O(1)
function moveZeroes(nums) {
let writeIdx = 0;
for (const v of nums) {
if (v !== 0) nums[writeIdx++] = v;
}
while (writeIdx < nums.length) nums[writeIdx++] = 0;
}Tradeoff: Two passes but easy to reason about. Works in-place.
2. Single-pass swap (optimal)
Maintain a slow pointer for the next non-zero slot. Sweep with fast; whenever nums[fast] != 0, swap with nums[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 at most n swaps. Demonstrates two-pointer fluency without extra allocations.
Snap-specific tips
Snap explicitly tests in-place editing. Verbalize the no-allocation guarantee and pick the single-pass swap variant. Bonus: connect this to compacting a Stories array when posts expire — same two-pointer shape.
Common mistakes
- Returning a new array — the prompt requires in-place.
- Forgetting to backfill zeros in the two-pass approach.
- Not testing when there are no zeros — slow == fast, swap with self is wasteful but correct.
Follow-up questions
An interviewer at Snap may pivot to one of these next:
- Move any sentinel value to the end.
- Stable partition with a predicate — same pattern.
- Implement Dutch National Flag (LC 75).
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why is the slow pointer not incremented on zeros?
Because slow marks the next slot waiting for a non-zero. Advancing it on zeros would overwrite that slot's purpose.
Is the swap necessary?
It's not strictly required for correctness — overwriting then filling zeros works too. The swap is just elegant and avoids the second pass.
Practice these live with InterviewChamp.AI
Drill Move Zeroes and other Snap interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →