JavaMediumTwo Pointers20 min

Move zeroes to the end stably

Print the array with all zeroes at the end while preserving nonzero order, separated by single spaces. Follow the stated ordering and edge-case conventions exactly. Interviewers use this task to probe algorithm selection, invariants, and boundary handling.

Input

n followed by n integers.

Output

Print the array with all zeroes at the end while preserving nonzero order, separated by single spaces.

Constraints

0 <= n <= 100000; values in [-1000000000,1000000000].

Example

Input

5 0 1 0 3 12

Output

1 3 12 0 0

Example 2 input

3 1 2 3

Output

1 2 3

This example exercises a further boundary or ordering case.

Public test cases (2)

  • Input

    5 0 1 0 3 12

    Expected output

    1 3 12 0 0
  • Input

    3 0 0 0

    Expected output

    0 0 0
Hints (2)
  1. Identify the state needed to avoid recomputing work for each element.
  2. Compact nonzero values into the front; Java's zero initialization supplies the suffix.

Target complexity: time O(n) · space O(n) array

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All Java programs