Coding problem · Easy · Basics
Move Zeroes to the End
Easy Algorithms & data structures
Return nums with all 0s moved to the end, keeping the relative order of the non-zero numbers.
Example 1
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2
Input: nums = [0] Output: [0]
Hints
Hint 1
Collect the non-zero numbers first, then add as many zeros as you skipped.
Hint 2
In place: a 'write' index marks where the next non-zero number goes.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Copy the non-zero values in order, then pad with zeros. The in-place version uses two pointers: write for the next non-zero slot, read scanning every element.
Reference solution
function moveZeroes(nums) {
const nonZero = nums.filter((n) => n !== 0);
return nonZero.concat(new Array(nums.length - nonZero.length).fill(0));
}
function moveZeroes(nums: number[]): number[] {
const nonZero = nums.filter((n) => n !== 0);
return nonZero.concat(new Array<number>(nums.length - nonZero.length).fill(0));
}
def move_zeroes(nums: list[int]) -> list[int]:
non_zero = [n for n in nums if n != 0]
return non_zero + [0] * (len(nums) - len(non_zero))
<?php
function moveZeroes(array $nums): array
{
$nonZero = array_values(array_filter($nums, fn ($n) => $n !== 0));
return array_merge($nonZero, array_fill(0, count($nums) - count($nonZero), 0));
}
class Solution {
public int[] moveZeroes(int[] nums) {
int[] out = new int[nums.length];
int write = 0;
for (int n : nums) if (n != 0) out[write++] = n;
return out;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy