Move Zeroes

25 min · moveZeroes()

An activity feed has real event IDs mixed with empty slots marked 0. You want the real events packed at the front without scrambling their order.

Given an integer array nums, move every zero to the end and return the resulting array. The non-zero values must be stable, meaning they appear in the same relative order as they did in the input.

A few ground rules:

  • Every input value stays in the result; you're rearranging, not deleting.
  • A negative number is still a non-zero value and keeps its place relative to the others.
  • Return an array with exactly the same length as nums.

Constraints

  • 1 <= nums.length <= 100_000
  • -2_147_483_648 <= nums[i] <= 2_147_483_647

Hints

Build the obvious version first

Collect the non-zero values in order, count how many slots remain, then append that many zeroes. What extra storage does that copy cost?

Give the next survivor a destination

Keep a write index for the next non-zero value. Scan from left to right; whenever you meet a non-zero value, place it at nums[write] and advance write.

Clean up the tail

Once every survivor has moved forward, all positions from write onward should be zero. Filling that suffix finishes the array without another allocation.

Follow-up

Can you preserve the order while using O(1) extra space, even when almost every value is zero?

Visible cases

Examples

Example 1

ready
Input
nums = [
  0,
  1,
  0,
  3,
  12
]
Expected
[
  1,
  3,
  12,
  0,
  0
]
Why
the non-zero values keep their order, then two zeroes fill the tail

Example 2

ready
Input
nums = [
  0,
  0,
  0,
  0
]
Expected
[
  0,
  0,
  0,
  0
]
Why
an all-zero array is already in its final form

Example 3

ready
Input
nums = [
  4,
  -2,
  9
]
Expected
[
  4,
  -2,
  9
]
Why
with no zeroes, every position stays unchanged

Interview signal

Asked at

MetaAmazonBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite