Push the empty slots to the end
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.
- Every non-zero value keeps its position relative to the others.
- All the zeros end up together at the end.
- The list comes back the same length it went in.
move_blanks_last(lines: list<int>) → list<int>
Where you start
def move_blanks_last(lines: list[int]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
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