Show problems as
Classic problem #283EasyArrayTwo Pointers

Move Zeroes

Real-world version: Compact Blank Cells
Tracked in this browser only
Read Move Zeroes on LeetCode(opens in a new tab)

The 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.

Python
def compact_blanks(cells: list[int]) -> list[int]:
Java
public int[] compactBlanks(int[] cells)