Move Zeroes
Real-world version: Compact Blank CellsThe statement here is our own: the same inputs, outputs and technique.
One column of a spreadsheet is held in the integer array cells. A cell nobody filled in is stored as 0; any other entry is a signed amount somebody typed, which may be negative.
Pack the typed amounts against the front of the column and push every blank behind them. The typed amounts have to come out in the same succession they went in, so only the blanks change position relative to anything else.
Rearrange cells itself using no more than a constant amount of extra space, then return cells.
Examples
Example 1
- Input
- cells = [4, 0, 5, 0, -3]
- Output
- [4, 5, -3, 0, 0]
The typed amounts still run 4, then 5, then -3, and the two blanks gather behind them.
Example 2
- Input
- cells = [0, -6, 0, 0, 3, 0, -1]
- Output
- [-6, 3, -1, 0, 0, 0, 0]
Four blanks slide back while -6, 3 and -1 hold the order they started in.
Example 3
- Input
- cells = [9, -2, 7]
- Output
- [9, -2, 7]
Nothing is blank here, so the column already satisfies the layout and comes back unchanged.
Constraints
- 1 <= cells.length <= 10^4
- -2^31 <= cells[i] <= 2^31 - 1
- Only a constant amount of extra space may be used
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def compact_blanks(cells: list[int]) -> list[int]:public int[] compactBlanks(int[] cells)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 9 test cases: 9 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's