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));
}

Was this page helpful?