Educatifu
Open menu

Move Zeroes

Mediumarraystwo-pointers

Move every 0 to the end of the array while keeping the order of the non-zero elements.

Input

Line 1: an integer n. Line 2: n integers.

Output

The array after moving all zeroes to the end, space-separated.

Examples

Example 1

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

Non-zeros 1, 3, 12 keep order; zeroes go last.

Example 2

Input
3
0 0 0
Output
0 0 0

All zeroes stay.

Example 3

Input
4
1 2 3 4
Output
1 2 3 4

No zeroes — unchanged.

Constraints

  • 1 <= n <= 10^5
  • -10^9 <= each value <= 10^9

Hints

Reveal hint 1

Keep the non-zero values in order, then pad the rest with zeroes.

Reveal hint 2

A single pass that writes non-zeros to the front achieves this in place.

Reference solution (spoiler — try it yourself first)

Approach

Collect the non-zero values in order, then append as many zeroes as were removed.

import sys
d = list(map(int, sys.stdin.read().split()))
n = d[0]
a = d[1:1 + n]
nz = [x for x in a if x != 0]
print(' '.join(map(str, nz + [0] * (len(a) - len(nz)))))

← All practice problems

Bring us the problem, not a perfect specification

Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.

  1. 01Share contextDescribe the workflow, constraint or risk.
  2. 02Clarify togetherWe identify missing facts and useful options.
  3. 03Choose a startAgree a focused assessment or delivery step.
Start a conversation