Drill

ProblemsGo › patterns

Push the empty slots to the end

easypatternsTwo pointersArraysGo

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>

Go 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

func moveBlanksLast(lines []int) []int {
	
}

Worked examples

CallResult
moveBlanksLast([]int{0, 1, 0, 3, 12})[]int{1, 3, 12, 0, 0}
moveBlanksLast([]int{1, 2, 3})[]int{1, 2, 3}
moveBlanksLast([]int{0, 0})[]int{0, 0}
moveBlanksLast([]int{})[]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 Go
func moveBlanksLast(lines []int) []int {
	out := make([]int, len(lines))
	write := 0
	for _, value := range lines {
	    if value != 0 {
	        out[write] = value
	        write++
	    }
	}
	return out
}

The same problem in another language

More patterns problems in Go