Drill

ProblemsPython › patterns

Push the empty slots to the end

easypatternsTwo pointersArraysPython

A picking list uses zero for a line that was cancelled. The screen keeps the live lines in order and pushes the blanks to the bottom.

move_blanks_last(lines: list<int>) → list<int>

Solve it in the editor →

Where you start

def move_blanks_last(lines: list[int]) -> list[int]:
    

Worked examples

CallResult
move_blanks_last([0, 1, 0, 3, 12])[1, 3, 12, 0, 0]
move_blanks_last([1, 2, 3])[1, 2, 3]
move_blanks_last([0, 0])[0, 0]
move_blanks_last([])[]

Hint

Keep a write index. Walk the list once copying every non-zero value to that index and advancing it; then fill what is left with zeros.

Reference solution in Python
def move_blanks_last(lines: list[int]) -> list[int]:
    out = [0] * len(lines)
    write = 0
    for value in lines:
        if value != 0:
            out[write] = value
            write += 1
    return out

The same problem in another language

More patterns problems in Python