PythonMediumTwo Pointers20 min
Move all zeros to the end
Perform the rearrangement in place in the core function. Return the full array, including its zeros. Interviewers use this problem to assess write each nonzero value at the next available position.
Input
First line: n. Second line: n space-separated integers (empty when n = 0).
Output
Print the result values separated by single spaces; print an empty line for an empty result.
Constraints
0 <= n <= 100000; -10^9 <= each value <= 10^9.
Example
Input
5 0 1 0 3 12
Output
1 3 12 0 0
Example 2 input
3 1 2 3
Output
1 2 3
An already compact array remains unchanged.
Public test cases (2)
Input
5 0 1 0 3 12
Expected output
1 3 12 0 0
Input
4 -1 0 -2 0
Expected output
-1 -2 0 0
Hints (2)
- Identify the state needed to avoid repeated work.
- Write each nonzero value at the next available position.
Target complexity: time O(n) · space O(1)
