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.
Move every 0 to the end of the array while keeping the order of the non-zero elements.
Line 1: an integer n.
Line 2: n integers.
The array after moving all zeroes to the end, space-separated.
Example 1
5 0 1 0 3 12
1 3 12 0 0
Non-zeros 1, 3, 12 keep order; zeroes go last.
Example 2
3 0 0 0
0 0 0
All zeroes stay.
Example 3
4 1 2 3 4
1 2 3 4
No zeroes — unchanged.
Keep the non-zero values in order, then pad the rest with zeroes.
A single pass that writes non-zeros to the front achieves this in place.
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)))))
Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.