Move Zeroes
Given an integer array nums, move all 0s 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. Use a slow pointer that marks where the next non-zero value should go and a fast pointer that scans for non-zero values, minimizing the total number of operations.
Constraints
- 1 ≤ nums.length ≤ 104
- -231 ≤ numsi ≤ 231 - 1
Example
nums = [0, 1, 0, 3, 12][1, 3, 12, 0, 0]Explanation All zeros are moved to the end while 1, 3 and 12 keep their original relative order.
Slow pointer marks the write slot, fast pointer scans
slow=0, fast=0 (value 0). Zero found — fast advances, slow stays.
What happens in this step
slow = 0, fast = 0 (value 0) nums[fast] == 0 fast advances without swapping since this element is already zero.
Steps to visualize
- Start slow and fast both at index 0.
- Advance fast through the array; whenever numsfast is non-zero, swap it into numsslow and move slow forward.
- Values already at or before slow are the non-zero values placed so far, in order.
- Continue until fast reaches the end of the array.
- Every slot from slow onward is now 0, and non-zero order was preserved.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
slow=0, fast=0 (value 0). Zero found — fast advances, slow stays.
What happens in this step
slow = 0, fast = 0 (value 0) nums[fast] == 0 fast advances without swapping since this element is already zero.
Solution
function moveZeroes(nums) {
let slow = 0;
for (let fast = 0; fast < nums.length; fast++) {
if (nums[fast] !== 0) {
const temp = nums[slow];
nums[slow] = nums[fast];
nums[fast] = temp;
slow++;
}
}
return nums;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [0, 1, 0, 3, 12] | [1, 3, 12, 0, 0] | example from the docstring |
nums = [0, 0, 0] | [0, 0, 0] | every element is zero |
nums = [1, 2, 3] | [1, 2, 3] | no zeros present, array is unchanged |
nums = [1, 2, 0, 0] | [1, 2, 0, 0] | zeros already positioned at the end |
nums = [0] | [0] | smallest valid input, a single zero |
nums = [0, 0, 1] | [1, 0, 0] | multiple leading zeros before the only non-zero value |