Move Zeroes

Easy

Problem

Move every 0 to the end of the array in place, keeping the relative order of the non-zero elements.

Example 1

Input:  [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Test cases

Case 1

Input:    [0,1,0,3,12]
Expected: [1,3,12,0,0]

Case 2

Input:    [0]
Expected: [0]

Case 3

Input:    [1,2]
Expected: [1,2]

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Swap non-zeros forward

Time O(n)Space O(1)

Keep a write pointer for the next non-zero slot; swapping preserves the order of non-zeros and pushes zeros back.

function moveZeroes(nums) {
let k = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
[nums[k], nums[i]] = [nums[i], nums[k]];
k++;
}
}
}