Heap algorithms
Heap algorithms use a binary heap to keep the current best element at the top: priority queues, top-K, and Dijkstra. In Go you implement heap.Interface on a slice, or keep a sorted slice when n is tiny.
Detailed Explanation
A heap gives O(log n) insert and O(log n) remove-min (or max), and O(1) peek. That is the right structure when you repeatedly need "the next cheapest edge" or "the largest of the values I have seen so far" while the set changes.
Top-K. To find the K largest, keep a min-heap of size K. Each new value smaller than the top is ignored; each larger one pops the top and pushes the new value. Final heap is the K largest. Time O(n log K), space O(K). For K = 1, this is a single variable. For K ≈ n, sort.
Dijkstra. Distances start at infinity. Push the source with distance 0. Pop the smallest distance; if you already finalized that node, skip. Relax neighbours and push the new distances. Go has no pairing-heap in std; container/heap plus a []int64 dist slice is the usual teaching version. You may push duplicate nodes; the first pop of a node is the best if weights are non-negative.
Merge K sorted lists. A heap of the current head of each list is O(N log K) to emit all N values. This is the same interface: Less compares heads.
Heap sort. heap.Init then Pop n times yields sorted order. sort.Slice is simpler and faster for a full sort. Use a heap when the access pattern is online (you do not have all items, or you need min while inserting).
What it costs. container/heap boxes pushed values as any unless you wrap carefully. Each push is O(log n) swaps. For integer IDs and small n, a slice plus slices.Sort on each query can beat a heap. For Dijkstra on dense graphs, the heap operations dominate; still start with container/heap before you write a 4-ary heap.
Code Examples
package main
import (
"container/heap"
"fmt"
)
type minH []int
func (h minH) Len() int { return len(h) }
func (h minH) Less(i, j int) bool { return h[i] < h[j] }
func (h minH) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *minH) Push(x any) { *h = append(*h, x.(int)) }
func (h *minH) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func kthLargest(nums []int, k int) int {
h := &minH{}
for _, n := range nums {
if h.Len() < k {
heap.Push(h, n)
continue
}
if n > (*h)[0] {
heap.Pop(h)
heap.Push(h, n)
}
}
return (*h)[0]
}
func main() {
fmt.Println(kthLargest([]int{3, 1, 5, 4}, 2)) // 4
}Common Gotchas
Dijkstra with a heap requires non-negative weights
negative edges need Bellman-Ford.
Popping without `Init` after bulk insert is wrong
call `heap.Init` or only use `Push`.
Duplicate entries in a Dijkstra heap are normal
skip if `d` is worse than `dist[u]`.
Top of the heap is index 0
do not sort the slice yourself.