U

33. Move All Zeros to End Preserving Relative Order

Easy

Problem Description

Given an array of NN integers, move all 0s to the end of the array while maintaining the relative order of the non-zero elements.

Input Format

  • •Line 1: An integer NN (1≤N≤1051 \le N \le 10^5).
  • •Line 2: NN space-separated integers A1,…,ANA_1, \dots, A_N.

Output Format

Print the NN space-separated integers of the modified array.

Example 1:
Input:
5
0 1 0 3 12
Output:
1 3 12 0 0
Explanation: Non-zero elements 1, 3, 12 maintain order; two 0s moved to the end.
Example 2:
Input:
3
0 0 0
Output:
0 0 0
Explanation: All zeros remain zeros.
Example 3:
Input:
4
1 2 3 4
Output:
1 2 3 4
Explanation: No zeros present.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online