Problems › JavaScript › patterns
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>
Where you start
function moveBlanksLast(lines) {
}
Worked examples
| Call | Result |
|---|---|
moveBlanksLast([0,1,0,3,12]) | [1,3,12,0,0] |
moveBlanksLast([1,2,3]) | [1,2,3] |
moveBlanksLast([0,0]) | [0,0] |
moveBlanksLast([]) | [] |
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 JavaScript
function moveBlanksLast(lines) {
const out = new Array(lines.length).fill(0);
let write = 0;
for (const value of lines) {
if (value !== 0) {
out[write] = value;
write += 1;
}
}
return out;
}