Unlike Python's heapq which works directly on lists, Go's container/heap requires you to define a custom type that satisfies the heap.Interface. This abstraction offers type safety and flexibility at the cost of initial boilerplate.
heap.InterfaceTo use a heap, your type (usually a slice) must implement five methods. Three come from sort.Interface, plus Push and Pop.
type Interface interface {
sort.Interface // Len, Less, Swap
Push(x any) // add x as element Len()
Pop() any // remove and return element Len() - 1.
}
This is the most confusing part for beginners. You do not call your methods directly. You call heap.Push, which handles the heap invariants (sifting up/down) and calls your implementation to physically modify the slice.
heap.Push(h, x): Calls h.Push(x) to append, then sifts up to correct position.heap.Pop(h): Swaps root with last element, sifts down new root, then calls h.Pop() to remove the last element.This is the standard pattern you will copy-paste for every heap implementation (until you use Generics).
import "container/heap"
// 1. Define the type
type IntHeap []int
// 2. Implement sort.Interface
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // < for MinHeap, > for MaxHeap
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
// 3. Implement Push (pointer receiver required to modify slice length)
func (h *IntHeap) Push(x any) {
*h = append(*h, x.(int))
}
// 4. Implement Pop (pointer receiver required)
func (h *IntHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
In this problem, we need a Min-Heap to keep track of the current smallest node among $k$ linked lists.
Next node, push that Next node into the heap.