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>
C++ 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
std::vector<int> moveBlanksLast(std::vector<int> lines) {
}
Worked examples
| Call | Result |
|---|---|
moveBlanksLast(std::vector<int>{0, 1, 0, 3, 12}) | std::vector<int>{1, 3, 12, 0, 0} |
moveBlanksLast(std::vector<int>{1, 2, 3}) | std::vector<int>{1, 2, 3} |
moveBlanksLast(std::vector<int>{0, 0}) | std::vector<int>{0, 0} |
moveBlanksLast(std::vector<int>{}) | std::vector<int>{} |
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 C++
std::vector<int> moveBlanksLast(std::vector<int> lines) {
std::vector<int> out(lines.size(), 0);
size_t write = 0;
for (int value : lines) {
if (value != 0) {
out[write] = value;
write++;
}
}
return out;
}