Drill

ProblemsTypeScript › patterns

Push the empty slots to the end

easypatternsTwo pointersArraysTypeScript

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>

Solve it in the editor →

Where you start

function moveBlanksLast(lines: number[]): number[] {
  
}

Worked examples

CallResult
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 TypeScript
function moveBlanksLast(lines: number[]): number[] {
  const out: number[] = new Array(lines.length).fill(0);
  let write = 0;
  for (const value of lines) {
    if (value !== 0) {
      out[write] = value;
      write += 1;
    }
  }
  return out;
}

The same problem in another language

More patterns problems in TypeScript