13. Chocolate Factory Empty Packets
Difficulty: easy · Array, Two Pointers
Problem
A chocolate factory packs chocolates into packets moving on a conveyor belt. The belt is represented by an array of `N` integers, where each value is the number of chocolates in a packet and `0` means the packet is empty. Push all empty packets to the end of the belt while keeping the non-empty packets in their original relative order. Print the resulting arrangement.
Input
- Line 1: the integer `N`. - Line 2: `N` space-separated integers `arr[0] ... arr[N-1]`.
Output
Print the `N` rearranged values on one line, separated by single spaces.
Example 1
Input: 8 4 5 0 1 9 0 5 0 Output: 4 5 1 9 5 0 0 0
Explanation: The three empty packets (0) move to the end; 4 5 1 9 5 keep their order.
Example 2
Input: 6 6 0 1 8 0 2 Output: 6 1 8 2 0 0
Explanation: Non-zero packets 6 1 8 2 stay in order, followed by the two zeros.
Constraints
- 1 <= N <= 10^5 - 0 <= arr[i] <= 10^9
Solutions are judged against 2 sample and 10 hidden tests. Sign in to solve it · All problems