Rearrange an array so that all zeros move to the end while the relative order of the non-zero elements is preserved.
Line 1: an integer n.
Line 2: n space-separated integers (present whenever n >= 1).
One line: the n integers after moving zeros to the end, space-separated.
Example 1
Input
6 0 1 0 3 12 0
Expected
1 3 12 0 0 0
Explanation
Non-zeros keep their order (1, 3, 12) and the three zeros go to the end: 1 3 12 0 0 0.
Example 2
Input
3 4 5 6
Expected
4 5 6
Explanation
There are no zeros, so the array is unchanged.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →