Lv.1arraytwo-pointers
Move Zeros to the End
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A bookshelf is given as shelf: each slot holds a book number, and an empty slot is 0. Move every book to the front
keeping the books in their original order, with all empty slots at the back, and return the resulting shelf.
Examples
| shelf | result |
|---|---|
[0, 1, 0, 3, 12] | [1, 3, 12, 0, 0] |
[0, 0, 0] | [0, 0, 0] |
[4, 2, 0, 2, 0, 7] | [4, 2, 2, 7, 0, 0] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(shelf: int[]) → int[]
Constraints
-
shelf.length -
shelf[i](0is an empty slot)
Expected complexity
- Time
- O(N)
- Space
- O(1) extra
Examples
| shelf | Expected |
|---|---|
[0,1,0,3,12] | [1,3,12,0,0] |
[0,0,0] | [0,0,0] |
[4,2,0,2,0,7] | [4,2,2,7,0,0] |
Hint
Hint
Keep a write pointer w. Scan left to right; for every non-zero value, write it to shelf[w] and advance w. Then fill from
w to the end with 0. Shifting the rest of the array (or swapping a zero step by step to the end) for every empty slot is
and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1308 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |