Skip to content
Optimal Lab

Arrays & Hashing · 102Easy

Move Zeroes

Given an array nums, move all zeroes to the end while keeping the relative order of the non-zero elements. You must do this IN PLACE without copying the array.

Constraints

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
  • You must do it in place, without making a copy of the array.

Examples

moveZeroes([0, 1, 0, 3, 12])    ->  [1, 3, 12, 0, 0]
moveZeroes([0])                 ->  [0]   // single element
moveZeroes([1, 2])              ->  [1, 2]   // already done
moveZeroes([0, 0, 0])           ->  [0, 0, 0]   // all zeroes
moveZeroes([0, -1, 0, 5])       ->  [-1, 5, 0, 0]   // negatives are not zeroes
moveZeroes([1, 0, 2, 0, 0, 3])  ->  [1, 2, 3, 0, 0, 0]   // relative order of 1,2,3 preserved

Edge cases

  • An array of all zeroes, or with no zeroes.
  • The order of the non-zero elements must be preserved.
  • FOLLOW-UP
  • Could you minimize the total number of operations done?
Show the target complexity (spoiler)
Naive
O(n^2) time — repeatedly find a zero and shift everything after it left by one.
Target
O(n) time, O(1) space — a write pointer for the next non-zero slot; after one pass, fill the tail with zeroes.

Solve it

By hand, in your editor. The runner checks answers and timing.

git clone https://github.com/sarmadkung/optimal-round
cd optimal-round
# open problems/01-arrays-hashing/102-move-zeroes.js
./practice c 102

Stuck? Watch the pattern run