Drill

ProblemsJava › patterns

Push the empty slots to the end

easypatternsTwo pointersArraysJava

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.

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

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

List<Integer> moveBlanksLast(List<Integer> lines) {
    
}

Worked examples

CallResult
moveBlanksLast(Main.<Integer>ls(0, 1, 0, 3, 12))Main.<Integer>ls(1, 3, 12, 0, 0)
moveBlanksLast(Main.<Integer>ls(1, 2, 3))Main.<Integer>ls(1, 2, 3)
moveBlanksLast(Main.<Integer>ls(0, 0))Main.<Integer>ls(0, 0)
moveBlanksLast(Main.<Integer>ls())Main.<Integer>ls()

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 Java
List<Integer> moveBlanksLast(List<Integer> lines) {
    List<Integer> out = new ArrayList<>();
    for (int value : lines) {
        if (value != 0) out.add(value);
    }
    while (out.size() < lines.size()) out.add(0);
    return out;
}

The same problem in another language

More patterns problems in Java