4. Move Zeroes

Difficulty: easy · Array, Two Pointers

Problem

Given an integer array `nums`, move all `0`s to the end of it while keeping the **relative order** of the non-zero elements. Print the array after the move.

Input

The first line holds `n`. The second holds `n` integers.

Output

Print the `n` integers of the rearranged array, separated by spaces.

Example 1

Input:
5
0 1 0 3 12
Output:
1 3 12 0 0

Explanation: The 3 non-zero values keep their order (1 3 12), followed by 2 zeros.

Example 2

Input:
1
0
Output:
0

Explanation: Every element is zero, so the array is unchanged.

Example 3

Input:
4
1 2 3 4
Output:
1 2 3 4

Explanation: There are no zeroes, so nothing moves.

Example 4

Input:
3
0 0 0
Output:
0 0 0

Explanation: Every element is zero, so the array is unchanged.

Example 5

Input:
6
4 0 0 -2 0 7
Output:
4 -2 7 0 0 0

Explanation: The 3 non-zero values keep their order (4 -2 7), followed by 3 zeros.

Example 6

Input:
2
0 5
Output:
5 0

Explanation: The 1 non-zero values keep their order (5), followed by 1 zero.

Example 7

Input:
7
9 0 8 0 7 0 6
Output:
9 8 7 6 0 0 0

Explanation: The 4 non-zero values keep their order (9 8 7 6), followed by 3 zeros.

Example 8

Input:
7
-86949 82471 0 -63993 -33179 0 51352
Output:
-86949 82471 -63993 -33179 51352 0 0

Explanation: The 5 non-zero values keep their order (-86949 82471 -63993 -33179 51352), followed by 2 zeros.

Example 9

Input:
8
0 0 50091 11575 -81641 0 0 -39806
Output:
50091 11575 -81641 -39806 0 0 0 0

Explanation: The 4 non-zero values keep their order (50091 11575 -81641 -39806), followed by 4 zeros.

Example 10

Input:
6
-26023 -95718 -59386 0 0 65242
Output:
-26023 -95718 -59386 65242 0 0

Explanation: The 4 non-zero values keep their order (-26023 -95718 -59386 65242), followed by 2 zeros.

Constraints

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

Solutions are judged against 10 sample and 5 hidden tests. Sign in to solve it · All problems