9. Push Zeros to the Back

A conveyor belt has a row of slots, and each slot holds some number of parcels. A slot with 0 is empty. To tidy the belt, every non-empty slot must slide towards the front, keeping the same order as before, while all the empty slots gather at the end.

Write a method moveZeroes that takes the array nums of slot contents and returns a new array of the same length in which all the non-zero values keep their original relative order and all the zeros come last.

Example 1

Input:
nums = [0,1,0,3,12]
Output:
[1,3,12,0,0]
Explanation:

The non-zero values 1, 3, 12 keep their order and slide to the front; the two zeros end up at the back.

Example 2

Input:
nums = [4,0,0,5]
Output:
[4,5,0,0]
Explanation:

4 stays first and 5 moves up next to it, followed by the two empty slots.

Constraints

1 ≤ nums.length ≤ 1000

-109 ≤ nums[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…