U

204. Array Containing Only 0s, 1s

Hard

Problem Description

Given an array containing only 0s, 1s, and 2s, sort it in one traversal without using a comparison-based sorting algorithm.

Input Format

  • •Line 1: An integer NN (0≤N≤1050 \le N \le 10^5), the number of nodes.
  • •Line 2: NN space-separated integers representing the node values in level-order. (Omitted if N=0N = 0).

Output Format

Print the computed integer scalar or space-separated traversal sequence.

Example 1:
Input:
5
1 2 3 4 5
Output:
4 2 5 1 3
Explanation: Processing tree nodes in standard order.
Example 2:
Input:
1
42
Output:
42
Explanation: Single root node evaluation.
Example 3:
Input:
0
Output:
0
Explanation: Empty tree evaluation returns 0.
Constraints:
  • 0 <= N <= 10^5
  • -10^9 <= node.val <= 10^9
  • Time complexity target: O(N)
  • Auxiliary space target: O(H) where H is tree height
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