Move Zeroes

easy

You're handed an integer array nums. Slide every 0 to the end of the array while keeping the relative order of the non-zero numbers exactly as it was.

The catch: you must do this in-place — no copying the answer into a brand-new array. Only the values inside nums may move.

For example, [0,1,0,3,12] becomes [1,3,12,0,0]: the non-zeros 1, 3, 12 stay in their original order, and both zeros collect at the back.

Hints

Try the easy version first: build the answer in a separate array, then copy it back. What goes in first, and what fills the rest?
Can you avoid the extra array? Think about a second pointer that only tracks where the next non-zero should land.
Two pointers: one scans every element, the other marks the boundary of the placed non-zeros. Swap when you find a non-zero.

Common doubts

The problem is defined as in-place — you mutate nums directly. Our judge reads the final state of nums (returned here for convenience), so both the mutation and the returned reference describe the same array.
Overwriting non-zeros to the front and then zero-filling the tail also works, but it takes two passes. Swapping does it in one pass and avoids extra writes when most elements are already non-zero — which is exactly what the follow-up asks for.

Interview follow-ups

Only swap when you actually meet a non-zero, and skip the swap when i == insert — the element is already in place, so a self-swap is wasted work.
Mirror the logic: scan from the right with the write pointer starting at the end, swapping non-zeros toward the back.

Fun facts

  • The two-pointer 'partition' here is the same engine behind Quicksort's partition step and the Dutch National Flag problem.
  • Move Zeroes is a classic warm-up for in-place array manipulation — the swap-only version is precisely the answer to its 'minimize operations' follow-up.

Asked at

MetaAmazonBloombergMicrosoftApple
Frequently Sometimes Occasionally
Example 1
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
The non-zeros 1, 3, 12 keep their order; the two 0's move to the end.
Example 2
Input: nums = [0]
Output: [0]
A single zero is already at the end.
Constraints

- 1 <= nums.length <= 10^4 - -2^31 <= nums[i] <= 2^31 - 1

Solve this problem →