Go heap programs give you the smallest or biggest item in a collection instantly, even while items keep arriving. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering container/heap, a heap built from scratch, heap sort, top K items, merging sorted lists, a priority queue and a running median.
You should first finish our Go sorting programs and Go stack and queue programs. The Go interface programs help too, because container/heap works through an interface. All programs were tested on Go 1.27.
What are Go Heap Programs?
Go heap programs use a heap, which is a tree kept inside a slice. In a min heap, every parent is smaller than or equal to its children, so the smallest item is always at index 0. A max heap is the same idea with the biggest item on top.
Think of a hospital emergency room. Patients do not wait in arrival order. The most serious case is always seen next, and a new serious case can jump the line. A heap is that waiting list.
Why Go Heap Programs Matter
Sorting the whole list every time an item arrives is slow. A heap does the same job far faster.
- Priority queues: job schedulers run the most urgent task first.
- Top K problems: “top 10 products” or “3 nearest drivers” without sorting everything.
- Merging: combining many sorted files or log streams into one.
- Interviews: Kth largest, top K frequent and merge K lists are classic heap questions.
How Go Heap Programs Work
A heap stores a complete binary tree in a slice. For the item at index i, its children sit at 2i+1 and 2i+2, and its parent sits at (i-1)/2. After a push, the new item moves up until its parent is smaller. After a pop, the last item moves to the top and sinks down.

The table below shows the cost of each heap operation.
| Operation | Cost | What happens |
|---|---|---|
| Look at the top | O(1) | Read index 0 |
| Push | O(log n) | Add at the end, move up |
| Pop | O(log n) | Move last to top, sink down |
| Build from n items | O(n) | heap.Init fixes the slice |
| Find any item | O(n) | A heap is not sorted |
Go Heap Programs with container/heap
These first Go heap programs use the standard library. You write five small methods, and container/heap does the hard work. The library needs these exact method names: Len, Less, Swap, Push and Pop.
Program 1: A Min Heap with container/heap
package main
import (
"container/heap"
"fmt"
)
// IntHeap is a slice of numbers that container/heap can keep in heap order.
type IntHeap []int
// Len tells the library how many items there are.
func (numbers IntHeap) Len() int { return len(numbers) }
// Less says if item i should sit closer to the top than item j. < makes a min heap.
func (numbers IntHeap) Less(i, j int) bool { return numbers[i] < numbers[j] }
// Swap exchanges two items. a, b = b, a swaps two values in one line.
func (numbers IntHeap) Swap(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }
// Push adds one item at the end. It needs a pointer (*IntHeap) because it changes the length.
func (numbers *IntHeap) Push(item any) { // any means a value of any type
*numbers = append(*numbers, item.(int)) // item.(int) gets the int back out of any
}
// Pop removes the last item. heap.Pop has already moved the smallest item there.
func (numbers *IntHeap) Pop() any {
old := *numbers // *numbers is the slice that the pointer points to
lastIndex := len(old) - 1
last := old[lastIndex]
*numbers = old[:lastIndex] // shrink the slice by one
return last
}
func main() {
numbers := &IntHeap{5, 2, 8} // & gives a pointer, which heap functions need
heap.Init(numbers) // arrange the slice into heap order
heap.Push(numbers, 1) // always call heap.Push, not numbers.Push
fmt.Println("min:", (*numbers)[0])
for numbers.Len() > 0 {
fmt.Print(heap.Pop(numbers), " ") // the smallest comes out first
}
fmt.Println()
}
min: 1
1 2 5 8
You never call your own methods directly. Instead, you call heap.Init, heap.Push and heap.Pop, and the library calls Len, Less and Swap to keep the order. Your own Push and Pop only add and remove at the end of the slice.
Program 2: A Max Heap by Flipping Less
package main
import (
"container/heap"
"fmt"
)
// MaxHeap keeps the biggest score on top.
type MaxHeap []int
// The five methods below are the ones container/heap needs, as in Program 1.
func (scores MaxHeap) Len() int { return len(scores) }
func (scores MaxHeap) Less(i, j int) bool { return scores[i] > scores[j] } // > puts the biggest on top
func (scores MaxHeap) Swap(i, j int) { scores[i], scores[j] = scores[j], scores[i] }
func (scores *MaxHeap) Push(item any) { *scores = append(*scores, item.(int)) }
func (scores *MaxHeap) Pop() any {
old := *scores
last := old[len(old)-1]
*scores = old[:len(old)-1]
return last
}
func main() {
scores := &MaxHeap{72, 95, 60, 88}
heap.Init(scores)
for i := 1; i <= 3; i++ {
fmt.Printf("rank %d: %d\n", i, heap.Pop(scores)) // %d prints a whole number
}
}
rank 1: 95
rank 2: 88
rank 3: 72
The only change from a min heap is > in Less. Now the bigger score counts as “first”, so it rises to the top. Everything else stays exactly the same.
Program 3: A Priority Queue of Tasks
package main
import (
"container/heap"
"fmt"
)
// Task is one job with a priority.
type Task struct {
Name string
Priority int // a higher number means more urgent
index int // position in the heap, needed by heap.Fix
}
// PriorityQueue keeps the most urgent task on top.
type PriorityQueue []*Task
func (queue PriorityQueue) Len() int { return len(queue) }
func (queue PriorityQueue) Less(i, j int) bool {
return queue[i].Priority > queue[j].Priority // higher priority comes first
}
func (queue PriorityQueue) Swap(i, j int) {
queue[i], queue[j] = queue[j], queue[i]
queue[i].index = i // keep each task's index up to date
queue[j].index = j
}
func (queue *PriorityQueue) Push(item any) {
task := item.(*Task)
task.index = len(*queue)
*queue = append(*queue, task)
}
func (queue *PriorityQueue) Pop() any {
old := *queue
task := old[len(old)-1]
old[len(old)-1] = nil // let the garbage collector free it
*queue = old[:len(old)-1]
return task
}
func main() {
queue := &PriorityQueue{}
backup := &Task{Name: "nightly backup", Priority: 1}
heap.Push(queue, &Task{Name: "send invoice", Priority: 3})
heap.Push(queue, backup)
heap.Push(queue, &Task{Name: "fix login bug", Priority: 5})
backup.Priority = 9 // the backup became urgent
heap.Fix(queue, backup.index) // move it to its new place in O(log n)
for queue.Len() > 0 {
task := heap.Pop(queue).(*Task) // .(*Task) turns the any value back into a task
fmt.Println(task.Priority, task.Name)
}
}
9 nightly backup
5 fix login bug
3 send invoice
Tasks go in with heap.Push, and the most urgent one always comes out first. Each task also stores its own index, and Swap keeps it correct. That is how heap.Fix finds the backup task after its priority changes, without searching the whole slice.
Go Heap Programs from Scratch
Interviewers often ask you to build a heap without the library. These Go heap programs show the index rules first, then the up and down moves in plain code.
Program 4: Find Parent and Child Positions
package main
import "fmt"
func main() {
// A min heap stored level by level in a slice.
numbers := []int{1, 3, 9, 7, 5}
for i := range numbers { // i is each position: 0, 1, 2, ...
left := 2*i + 1 // position of the left child
right := 2*i + 2 // position of the right child
fmt.Print("index ", i, " value ", numbers[i])
if left < len(numbers) {
fmt.Print(" | left child ", numbers[left])
}
if right < len(numbers) {
fmt.Print(" | right child ", numbers[right])
}
if i > 0 {
parent := (i - 1) / 2 // whole number division drops the remainder
fmt.Print(" | parent ", numbers[parent])
}
fmt.Println()
}
}
index 0 value 1 | left child 3 | right child 9
index 1 value 3 | left child 7 | right child 5 | parent 1
index 2 value 9 | parent 1
index 3 value 7 | parent 3
index 4 value 5 | parent 3
This program shows the tree hiding inside the slice. For each position, you compute the children with 2*i + 1 and 2*i + 2, and the parent with (i - 1) / 2. A child only exists if its position is still inside the slice.
Program 5: Check if a Slice is a Min Heap
package main
import "fmt"
// isMinHeap checks that every parent is smaller than or equal to its children.
func isMinHeap(numbers []int) bool {
for child := 1; child < len(numbers); child++ {
parent := (child - 1) / 2
if numbers[parent] > numbers[child] {
return false // this parent is bigger than its child
}
}
return true // every parent passed the test
}
func main() {
fmt.Println(isMinHeap([]int{1, 3, 9, 7, 5}))
fmt.Println(isMinHeap([]int{1, 2, 3, 4, 5})) // a sorted slice is always a heap
fmt.Println(isMinHeap([]int{4, 1, 3}))
}
true
true
false
You visit every item except the root and compare it with its parent. If any parent is bigger, the heap rule is broken, so you return false. In the last slice, 4 sits above 1, which is why the answer is false.
Program 6: Build a Min Heap by Hand
package main
import "fmt"
// MinHeap keeps the smallest value at index 0 of its slice.
type MinHeap struct {
items []int
}
// Push adds at the end, then swaps with the parent while it is smaller.
func (minHeap *MinHeap) Push(value int) {
items := append(minHeap.items, value)
child := len(items) - 1 // the new item starts at the end
for child > 0 {
parent := (child - 1) / 2
if items[parent] <= items[child] {
break // the order is correct, so stop
}
items[parent], items[child] = items[child], items[parent] // swap
child = parent // keep moving up
}
minHeap.items = items
}
// Pop takes the root, moves the last item to the top, then sinks it down.
func (minHeap *MinHeap) Pop() int {
items := minHeap.items
top := items[0]
lastIndex := len(items) - 1
items[0] = items[lastIndex] // Step 1: move the last item to the top
items = items[:lastIndex] // Step 2: shrink the slice
current := 0
for { // Step 3: sink the top item until both children are bigger
smallest := current
left := 2*current + 1
right := 2*current + 2
if left < len(items) && items[left] < items[smallest] {
smallest = left
}
if right < len(items) && items[right] < items[smallest] {
smallest = right
}
if smallest == current {
break // both children are bigger, so stop
}
items[current], items[smallest] = items[smallest], items[current]
current = smallest
}
minHeap.items = items
return top
}
func main() {
var minHeap MinHeap
for _, value := range []int{7, 3, 9, 1, 5} {
minHeap.Push(value)
}
fmt.Println("slice:", minHeap.items)
for len(minHeap.items) > 0 {
fmt.Print(minHeap.Pop(), " ")
}
fmt.Println()
}
slice: [1 3 9 7 5]
1 3 5 7 9
Push adds the value at the end and swaps it up while its parent is bigger. Pop saves the root, moves the last item to the top and swaps it down with its smaller child. The slice [1 3 9 7 5] is not sorted, but every parent is smaller than its children. That is all a heap promises.

Program 7: Heap Sort
package main
import "fmt"
// sink moves the item at index down inside a max heap of the first size items.
func sink(numbers []int, index, size int) {
for {
largest := index
left := 2*index + 1
right := 2*index + 2
if left < size && numbers[left] > numbers[largest] {
largest = left
}
if right < size && numbers[right] > numbers[largest] {
largest = right
}
if largest == index {
return // both children are smaller, so stop
}
numbers[index], numbers[largest] = numbers[largest], numbers[index]
index = largest
}
}
// heapSort sorts the slice from small to big, in place.
func heapSort(numbers []int) {
size := len(numbers)
// Step 1: build a max heap from the bottom up.
for i := size/2 - 1; i >= 0; i-- {
sink(numbers, i, size)
}
// Step 2: move the max to the end, then shrink the heap by one.
for end := size - 1; end > 0; end-- {
numbers[0], numbers[end] = numbers[end], numbers[0]
sink(numbers, 0, end)
}
}
func main() {
numbers := []int{12, 3, 17, 8, 34, 25, 1}
heapSort(numbers)
fmt.Println(numbers)
}
[1 3 8 12 17 25 34]
First, you turn the slice into a max heap, so the biggest value is at index 0. Then you swap it to the end and sink the new top inside the smaller heap. Heap sort is always O(n log n) and sorts in place with O(1) extra memory. It is not stable, so equal items may change order.
Most Asked Interview Go Heap Programs
These Go heap programs solve the top K and merging questions that appear in most coding rounds.
Program 8: Kth Largest Element
package main
import (
"container/heap"
"fmt"
)
// IntHeap is a min heap of numbers (the five methods from Program 1).
type IntHeap []int
func (numbers IntHeap) Len() int { return len(numbers) }
func (numbers IntHeap) Less(i, j int) bool { return numbers[i] < numbers[j] }
func (numbers IntHeap) Swap(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }
func (numbers *IntHeap) Push(item any) { *numbers = append(*numbers, item.(int)) }
func (numbers *IntHeap) Pop() any {
old := *numbers
last := old[len(old)-1]
*numbers = old[:len(old)-1]
return last
}
// kthLargest keeps a min heap of the kth biggest values seen so far.
// The smallest of those values is the answer.
func kthLargest(numbers []int, kth int) int {
best := &IntHeap{}
for _, value := range numbers {
heap.Push(best, value)
if best.Len() > kth {
heap.Pop(best) // drop the smallest, keep only kth items
}
}
return (*best)[0]
}
func main() {
fmt.Println(kthLargest([]int{3, 2, 1, 5, 6, 4}, 2))
fmt.Println(kthLargest([]int{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4))
}
5
4
The heap best holds only the biggest values seen so far. Whenever it grows too big, you pop the smallest one away, so the top is the answer. The heap never holds more than k items, so this is O(n log k), which is why Go heap programs win on large data. For a stream of millions of numbers with k = 10, that is far faster than sorting.
Program 9: Top K Frequent Words
package main
import (
"container/heap"
"fmt"
"strings"
)
// wordCount pairs a word with how many times it appears.
type wordCount struct {
word string
count int
}
// countHeap is a min heap: the "weakest" word is on top, so we can drop it.
type countHeap []wordCount
func (entries countHeap) Len() int { return len(entries) }
func (entries countHeap) Less(i, j int) bool {
if entries[i].count != entries[j].count {
return entries[i].count < entries[j].count
}
return entries[i].word > entries[j].word // on a tie, the later word is weaker
}
func (entries countHeap) Swap(i, j int) { entries[i], entries[j] = entries[j], entries[i] }
func (entries *countHeap) Push(item any) { *entries = append(*entries, item.(wordCount)) }
func (entries *countHeap) Pop() any {
old := *entries
last := old[len(old)-1]
*entries = old[:len(old)-1]
return last
}
// topK returns the howMany most frequent words, most frequent first.
func topK(text string, howMany int) []string {
counts := map[string]int{}
for _, word := range strings.Fields(text) { // Fields splits the text at spaces
counts[word]++
}
strongest := &countHeap{}
for word, count := range counts {
heap.Push(strongest, wordCount{word: word, count: count})
if strongest.Len() > howMany {
heap.Pop(strongest) // drop the weakest word
}
}
result := make([]string, strongest.Len())
for i := len(result) - 1; i >= 0; i-- { // pop weakest first, fill from the back
result[i] = heap.Pop(strongest).(wordCount).word
}
return result
}
func main() {
fmt.Println(topK("go is fun go is fast go rocks", 2))
fmt.Println(topK("b a c a b c d", 3))
}
[go is]
[a b c]
First, a map counts each word. Then the heap keeps only the strongest words and drops the weakest one each time it grows too big. In Go heap programs that read maps, a tie rule is a must. The tie rule on word makes the answer the same on every run, even though map order is random.
Program 10: Merge K Sorted Slices
package main
import (
"container/heap"
"fmt"
)
// entry remembers a value, which list it came from and its position there.
type entry struct {
value int
listIndex int
position int
}
// entryHeap is a min heap ordered by value.
type entryHeap []entry
func (entries entryHeap) Len() int { return len(entries) }
func (entries entryHeap) Less(i, j int) bool { return entries[i].value < entries[j].value }
func (entries entryHeap) Swap(i, j int) { entries[i], entries[j] = entries[j], entries[i] }
func (entries *entryHeap) Push(item any) { *entries = append(*entries, item.(entry)) }
func (entries *entryHeap) Pop() any {
old := *entries
last := old[len(old)-1]
*entries = old[:len(old)-1]
return last
}
// mergeK joins many sorted slices into one sorted slice.
func mergeK(lists [][]int) []int {
fronts := &entryHeap{}
// Step 1: push the first item of each list.
for i, list := range lists {
if len(list) > 0 {
heap.Push(fronts, entry{value: list[0], listIndex: i, position: 0})
}
}
// Step 2: pop the smallest, then push the next item from the same list.
var merged []int
for fronts.Len() > 0 {
smallest := heap.Pop(fronts).(entry)
merged = append(merged, smallest.value)
nextPosition := smallest.position + 1
list := lists[smallest.listIndex]
if nextPosition < len(list) {
heap.Push(fronts, entry{value: list[nextPosition], listIndex: smallest.listIndex, position: nextPosition})
}
}
return merged
}
func main() {
fmt.Println(mergeK([][]int{{1, 4, 9}, {2, 3, 10}, {5, 6}}))
}
[1 2 3 4 5 6 9 10]
The heap holds the front item of every list. Each round, you pop the smallest one and push the next item from the same list. The heap holds at most one item per list, so the total cost is O(n log k) for n items across k lists. This is how databases merge sorted runs on disk.
Program 11: Running Median with Two Heaps
package main
import (
"container/heap"
"fmt"
)
// NumberHeap is a min heap, or a max heap when isMax is true.
type NumberHeap struct {
items []int
isMax bool // true: biggest on top, false: smallest on top
}
func (half NumberHeap) Len() int { return len(half.items) }
func (half NumberHeap) Less(i, j int) bool {
if half.isMax {
return half.items[i] > half.items[j]
}
return half.items[i] < half.items[j]
}
func (half NumberHeap) Swap(i, j int) { half.items[i], half.items[j] = half.items[j], half.items[i] }
func (half *NumberHeap) Push(item any) { half.items = append(half.items, item.(int)) }
func (half *NumberHeap) Pop() any {
last := half.items[len(half.items)-1]
half.items = half.items[:len(half.items)-1]
return last
}
func main() {
low := &NumberHeap{isMax: true} // smaller half, biggest on top
high := &NumberHeap{} // bigger half, smallest on top
for _, value := range []int{5, 15, 1, 3, 8} {
// Step 1: add to the low half, then move its biggest to the high half.
heap.Push(low, value)
heap.Push(high, heap.Pop(low))
// Step 2: keep low the same size as high, or one bigger.
if high.Len() > low.Len() {
heap.Push(low, heap.Pop(high))
}
// Step 3: read the median from the two tops.
if low.Len() > high.Len() {
fmt.Printf("add %d -> median %d\n", value, low.items[0])
} else {
median := float64(low.items[0]+high.items[0]) / 2 // float64 keeps the .5
fmt.Printf("add %d -> median %.1f\n", value, median) // %.1f prints one decimal place
}
}
}
add 5 -> median 5
add 15 -> median 10.0
add 1 -> median 5
add 3 -> median 4.0
add 8 -> median 5
The low heap holds the smaller half of the numbers, with its biggest on top. The high heap holds the bigger half, with its smallest on top. So the two tops always sit in the middle of all numbers seen so far. One isMax field lets the same type work as a min heap or a max heap.
Program 12: K Closest Points to the Origin
package main
import (
"container/heap"
"fmt"
"slices"
)
// Point is a spot on a map. x and y are the usual names for its two coordinates.
type Point struct{ x, y int }
// squaredDistance measures how far a point is from (0, 0). No square root is needed to compare.
func squaredDistance(point Point) int { return point.x*point.x + point.y*point.y }
// farHeap is a max heap by distance, so the farthest point is dropped first.
type farHeap []Point
func (points farHeap) Len() int { return len(points) }
func (points farHeap) Less(i, j int) bool {
return squaredDistance(points[i]) > squaredDistance(points[j])
}
func (points farHeap) Swap(i, j int) { points[i], points[j] = points[j], points[i] }
func (points *farHeap) Push(item any) { *points = append(*points, item.(Point)) }
func (points *farHeap) Pop() any {
old := *points
last := old[len(old)-1]
*points = old[:len(old)-1]
return last
}
// byDistance compares two points for sorting, nearest first.
func byDistance(first, second Point) int {
return squaredDistance(first) - squaredDistance(second)
}
func main() {
drivers := []Point{{3, 3}, {5, -1}, {-2, 4}, {1, 1}, {0, 2}}
closest := &farHeap{}
for _, driver := range drivers {
heap.Push(closest, driver)
if closest.Len() > 3 {
heap.Pop(closest) // drop the farthest, keep the 3 nearest
}
}
nearest := []Point(*closest) // turn the heap back into a plain slice
slices.SortFunc(nearest, byDistance) // nearest first for printing
fmt.Println(nearest)
}
[{1 1} {0 2} {3 3}]
The heap keeps the three nearest drivers, with the farthest of them on top. When a fourth driver arrives, you pop the farthest one away. Comparing squared distances gives the same order as real distances and avoids slow math.Sqrt calls. Ride apps use this idea to find the nearest drivers.
Program 13: Minimum Meeting Rooms
package main
import (
"container/heap"
"fmt"
"slices"
)
// IntHeap is a min heap of numbers (the five methods from Program 1).
type IntHeap []int
func (numbers IntHeap) Len() int { return len(numbers) }
func (numbers IntHeap) Less(i, j int) bool { return numbers[i] < numbers[j] }
func (numbers IntHeap) Swap(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }
func (numbers *IntHeap) Push(item any) { *numbers = append(*numbers, item.(int)) }
func (numbers *IntHeap) Pop() any {
old := *numbers
last := old[len(old)-1]
*numbers = old[:len(old)-1]
return last
}
// byStart compares two meetings by start time, for sorting.
func byStart(first, second [2]int) int { return first[0] - second[0] }
// minRooms sorts meetings by start time and keeps a heap of end times.
// Each meeting is [2]int: index 0 is the start, index 1 is the end.
func minRooms(meetings [][2]int) int {
slices.SortFunc(meetings, byStart)
endTimes := &IntHeap{}
for _, meeting := range meetings {
start := meeting[0]
end := meeting[1]
if endTimes.Len() > 0 && (*endTimes)[0] <= start {
heap.Pop(endTimes) // the earliest room is free again, so reuse it
}
heap.Push(endTimes, end)
}
return endTimes.Len() // rooms still in use at the busiest time
}
func main() {
fmt.Println(minRooms([][2]int{{9, 10}, {9, 12}, {10, 11}, {11, 13}}))
fmt.Println(minRooms([][2]int{{9, 10}, {10, 11}}))
}
2
1
You sort the meetings by start time, then go through them in order. The heap top is the meeting that ends soonest. If it ends before the next one starts, that room is reused instead of booking a new one.
Program 14: A Generic Heap with cmp.Ordered
package main
import (
"cmp"
"fmt"
)
// Heap[T] is a min heap for any ordered type T, with no interface methods.
type Heap[T cmp.Ordered] struct {
items []T
}
// Push adds at the end, then moves the value up while it is smaller than its parent.
func (minHeap *Heap[T]) Push(value T) {
items := append(minHeap.items, value)
child := len(items) - 1
for child > 0 {
parent := (child - 1) / 2
if items[parent] <= items[child] {
break
}
items[parent], items[child] = items[child], items[parent]
child = parent
}
minHeap.items = items
}
// Pop removes the smallest value and sinks the new top down.
func (minHeap *Heap[T]) Pop() T {
items := minHeap.items
top := items[0]
lastIndex := len(items) - 1
items[0] = items[lastIndex]
items = items[:lastIndex]
current := 0
for {
smallest := current
left := 2*current + 1
right := 2*current + 2
if left < len(items) && items[left] < items[smallest] {
smallest = left
}
if right < len(items) && items[right] < items[smallest] {
smallest = right
}
if smallest == current {
break
}
items[current], items[smallest] = items[smallest], items[current]
current = smallest
}
minHeap.items = items
return top
}
func main() {
var words Heap[string] // T is string here
for _, word := range []string{"pear", "apple", "mango", "fig"} {
words.Push(word)
}
for len(words.items) > 0 {
fmt.Print(words.Pop(), " ")
}
fmt.Println()
}
apple fig mango pear
This is the hand-made heap from Program 6, but with a type parameter T. The rule cmp.Ordered means T must support <, so it works for ints, floats and strings without any any conversions. See our generics post for more on cmp.Ordered.
Heap vs Sorted Slice in Go Heap Programs
Both can give you the smallest item, but they cost very different amounts as items arrive. The table below compares them.
| Feature | Heap | Sorted slice |
|---|---|---|
| Get the smallest | O(1) | O(1) |
| Add one item | O(log n) | O(n), shifts items |
| Remove the smallest | O(log n) | O(n) from the front |
| Fully sorted | No, only the top is known | Yes |
| Best for | Items keep arriving | Data that rarely changes |
A simple rule helps. If items keep arriving and you only need the top, use a heap. If you need the whole list in order once, just sort it.
Common Mistakes in Go Heap Programs
- Calling numbers.Push instead of heap.Push: your method only appends and breaks the heap order.
- Value receivers on Push and Pop: they must be pointer receivers to change the length.
- Forgetting heap.Init: a slice you fill directly is not a heap until you call it.
- Reading the last item as the max: only index 0 is known, the rest is not sorted.
- No tie-breaker: equal priorities can come out in any order without one.
Best Practices for Go Heap Programs
- Keep the heap size at k for top K problems, so the cost is O(n log k).
- Store an index field when you need
heap.Fixorheap.Remove. - Set popped pointer slots to nil so the garbage collector can free them.
- Use a min heap for “largest k” and a max heap for “smallest k”.
- Write a generic heap when you use the same pattern for many types.
Go Heap Programs Interview Questions and Answers
These are the heap questions interviewers ask most, and they build on the Go heap programs above. Each code answer is complete, with real output from Go 1.27.
Concept Questions on Go Heap Programs
Q1. Which five methods does heap.Interface need?
Len, Less and Swap come from sort.Interface, plus Push(item any) and Pop() any. The package calls them for you.
Q2. Is a heap the same as a sorted array?
No. A heap only promises that each parent beats its children. The slice [1 3 9 7 5] is a valid min heap but is not sorted.
Q3. What does this program print?
package main
import (
"container/heap"
"fmt"
"sort"
)
// NumberHeap embeds sort.IntSlice, which already has Len, Less and Swap.
// So we only add Push and Pop.
type NumberHeap struct{ sort.IntSlice }
func (numbers *NumberHeap) Push(item any) {
numbers.IntSlice = append(numbers.IntSlice, item.(int))
}
func (numbers *NumberHeap) Pop() any {
old := numbers.IntSlice
last := old[len(old)-1]
numbers.IntSlice = old[:len(old)-1]
return last
}
func main() {
numbers := &NumberHeap{sort.IntSlice{4, 1, 3}}
heap.Init(numbers)
heap.Push(numbers, 2)
fmt.Println(heap.Pop(numbers), heap.Pop(numbers), numbers.Len())
}
1 2 2
Embedding sort.IntSlice saves three methods. The heap holds 1, 2, 3 and 4, and the two pops take out 1 and 2. After that, 3 and 4 are left, so the length is 2.
Q4. What is the time to build a heap from n items?
heap.Init takes O(n), not O(n log n). Most nodes are near the bottom and only sink a short way, so the total work adds up to linear time.
Coding Questions
Q5. How do you sort strings by length with a heap?
package main
import (
"container/heap"
"fmt"
)
// ByLength is a min heap of words: shorter words come out first.
type ByLength []string
func (words ByLength) Len() int { return len(words) }
func (words ByLength) Less(i, j int) bool {
if len(words[i]) != len(words[j]) {
return len(words[i]) < len(words[j]) // shorter first
}
return words[i] < words[j] // same length: alphabetical
}
func (words ByLength) Swap(i, j int) { words[i], words[j] = words[j], words[i] }
func (words *ByLength) Push(item any) { *words = append(*words, item.(string)) }
func (words *ByLength) Pop() any {
old := *words
last := old[len(old)-1]
*words = old[:len(old)-1]
return last
}
func main() {
fruits := &ByLength{"banana", "kiwi", "fig", "apple", "pear"}
heap.Init(fruits)
for fruits.Len() > 0 {
fmt.Print(heap.Pop(fruits), " ")
}
fmt.Println()
}
fig kiwi pear apple banana
All the ordering rules live in Less. Here it compares lengths first and uses the alphabet only on a tie. Change that one method, and the heap order changes.
Q6. What happens if you call heap.Pop on an empty heap?
package main
import (
"container/heap"
"sort"
)
// NumberHeap embeds sort.IntSlice and adds Push and Pop.
type NumberHeap struct{ sort.IntSlice }
func (numbers *NumberHeap) Push(item any) {
numbers.IntSlice = append(numbers.IntSlice, item.(int))
}
func (numbers *NumberHeap) Pop() any {
old := numbers.IntSlice
last := old[len(old)-1]
numbers.IntSlice = old[:len(old)-1]
return last
}
func main() {
numbers := &NumberHeap{}
heap.Pop(numbers) // nothing to pop, so this panics
}
panic: runtime error: index out of range
heap.Pop does not check the length for you. Always test numbers.Len() > 0 before popping.
Q7. How do you remove any item from the middle of a heap?
Keep the item’s index, as in Program 3, and call heap.Remove(queue, index). It swaps the item with the last one, removes it and then fixes the order in O(log n).
Design Questions
Q8. How would you find the top 10 search terms from a log of one billion lines?
Count terms with a map, or with several maps in parallel if needed. Then push each term into a min heap of size 10, dropping the smallest each time. Memory stays small, and the cost is O(n log 10).
Q9. When is sorting better than a heap?
When you need all items in order once and no new items arrive. slices.Sort is simple and very fast for that case.
Q10. How does Go’s timer system relate to heaps?
The Go runtime keeps timers in a heap ordered by when they fire. So the next timer to fire is always at the top, and adding a timer costs O(log n).
Practice Task
To practise Go heap programs, write a task scheduler that reads jobs as name priority lines, such as deploy 5, email 1 and backup 3. Print them in priority order, highest first, with equal priorities in alphabetical order. Hint: put the tie rule inside Less.
Official Resources
Quick Recap
- Go heap programs keep the smallest or biggest item at index 0 of a slice.
- Push and pop cost O(log n), and looking at the top costs O(1).
container/heapneeds Len, Less, Swap, Push and Pop.- A heap of size k solves top K problems in O(n log k).
- Two heaps give a running median, and an index field enables heap.Fix.
What’s Next?
Next, we build trees where every node can have children on both sides. Read Go tree programs, with binary search trees, traversals, height and lowest common ancestor. For more practice, see the Go stack and queue programs.


