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.
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.
Where you start
List<Integer> moveBlanksLast(List<Integer> lines) {
}
Worked examples
| Call | Result |
|---|---|
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;
}