All problems
0015EasyArrayTwo Pointers

Compact Blank Cells

Tracked in this browser only
Write code

Trains the technique from

LeetCode 283Move Zeroes

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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