{"id":850,"date":"2026-10-10T13:00:00","date_gmt":"2026-10-10T07:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/"},"modified":"2026-11-29T01:29:25","modified_gmt":"2026-11-28T19:59:25","slug":"go-heap-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/","title":{"rendered":"Go Heap Programs: Priority Queue, Top K and Running Median"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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 <code>container\/heap<\/code>, a heap built from scratch, heap sort, top K items, merging sorted lists, a priority queue and a running median.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You should first finish our <a href=\"https:\/\/smitabharat.com\/blog\/go-sorting-programs\/\">Go sorting programs<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-stack-and-queue-programs\/\">Go stack and queue programs<\/a>. The <a href=\"https:\/\/smitabharat.com\/blog\/go-interface-programs\/\">Go interface programs<\/a> help too, because <code>container\/heap<\/code> works through an interface. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Heap Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Heap Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sorting the whole list every time an item arrives is slow. A heap does the same job far faster.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Priority queues:<\/strong> job schedulers run the most urgent task first.<\/li>\n\n\n<li><strong>Top K problems:<\/strong> &#8220;top 10 products&#8221; or &#8220;3 nearest drivers&#8221; without sorting everything.<\/li>\n\n\n<li><strong>Merging:<\/strong> combining many sorted files or log streams into one.<\/li>\n\n\n<li><strong>Interviews:<\/strong> Kth largest, top K frequent and merge K lists are classic heap questions.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Heap Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-1024x640.png\" alt=\"Go heap programs diagram showing a min heap tree and the same values stored in a slice\" class=\"wp-image-848\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">A min heap keeps the smallest value at the root, and the tree is stored level by level in a slice.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below shows the cost of each heap operation.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Operation<\/th><th>Cost<\/th><th>What happens<\/th><\/tr><\/thead><tbody><tr><td>Look at the top<\/td><td>O(1)<\/td><td>Read index 0<\/td><\/tr><tr><td>Push<\/td><td>O(log n)<\/td><td>Add at the end, move up<\/td><\/tr><tr><td>Pop<\/td><td>O(log n)<\/td><td>Move last to top, sink down<\/td><\/tr><tr><td>Build from n items<\/td><td>O(n)<\/td><td>heap.Init fixes the slice<\/td><\/tr><tr><td>Find any item<\/td><td>O(n)<\/td><td>A heap is not sorted<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Go Heap Programs with container\/heap<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go heap programs use the standard library. You write five small methods, and <code>container\/heap<\/code> does the hard work. The library needs these exact method names: <code>Len<\/code>, <code>Less<\/code>, <code>Swap<\/code>, <code>Push<\/code> and <code>Pop<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: A Min Heap with container\/heap<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ IntHeap is a slice of numbers that container\/heap can keep in heap order.\ntype IntHeap []int\n\n\/\/ Len tells the library how many items there are.\nfunc (numbers IntHeap) Len() int { return len(numbers) }\n\n\/\/ Less says if item i should sit closer to the top than item j. &lt; makes a min heap.\nfunc (numbers IntHeap) Less(i, j int) bool { return numbers[i] &lt; numbers[j] }\n\n\/\/ Swap exchanges two items. a, b = b, a swaps two values in one line.\nfunc (numbers IntHeap) Swap(i, j int) { numbers[i], numbers[j] = numbers[j], numbers[i] }\n\n\/\/ Push adds one item at the end. It needs a pointer (*IntHeap) because it changes the length.\nfunc (numbers *IntHeap) Push(item any) { \/\/ any means a value of any type\n    *numbers = append(*numbers, item.(int)) \/\/ item.(int) gets the int back out of any\n}\n\n\/\/ Pop removes the last item. heap.Pop has already moved the smallest item there.\nfunc (numbers *IntHeap) Pop() any {\n    old := *numbers \/\/ *numbers is the slice that the pointer points to\n    lastIndex := len(old) - 1\n    last := old[lastIndex]\n    *numbers = old[:lastIndex] \/\/ shrink the slice by one\n    return last\n}\n\nfunc main() {\n    numbers := &amp;IntHeap{5, 2, 8} \/\/ &amp; gives a pointer, which heap functions need\n    heap.Init(numbers)           \/\/ arrange the slice into heap order\n    heap.Push(numbers, 1)        \/\/ always call heap.Push, not numbers.Push\n    fmt.Println(\"min:\", (*numbers)[0])\n\n    for numbers.Len() &gt; 0 {\n        fmt.Print(heap.Pop(numbers), \" \") \/\/ the smallest comes out first\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>min: 1\n1 2 5 8<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You never call your own methods directly. Instead, you call <code>heap.Init<\/code>, <code>heap.Push<\/code> and <code>heap.Pop<\/code>, and the library calls <code>Len<\/code>, <code>Less<\/code> and <code>Swap<\/code> to keep the order. Your own <code>Push<\/code> and <code>Pop<\/code> only add and remove at the end of the slice.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: A Max Heap by Flipping Less<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ MaxHeap keeps the biggest score on top.\ntype MaxHeap []int\n\n\/\/ The five methods below are the ones container\/heap needs, as in Program 1.\nfunc (scores MaxHeap) Len() int           { return len(scores) }\nfunc (scores MaxHeap) Less(i, j int) bool { return scores[i] &gt; scores[j] } \/\/ &gt; puts the biggest on top\nfunc (scores MaxHeap) Swap(i, j int)      { scores[i], scores[j] = scores[j], scores[i] }\nfunc (scores *MaxHeap) Push(item any)     { *scores = append(*scores, item.(int)) }\nfunc (scores *MaxHeap) Pop() any {\n    old := *scores\n    last := old[len(old)-1]\n    *scores = old[:len(old)-1]\n    return last\n}\n\nfunc main() {\n    scores := &amp;MaxHeap{72, 95, 60, 88}\n    heap.Init(scores)\n    for i := 1; i &lt;= 3; i++ {\n        fmt.Printf(\"rank %d: %d\\n\", i, heap.Pop(scores)) \/\/ %d prints a whole number\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>rank 1: 95\nrank 2: 88\nrank 3: 72<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The only change from a min heap is <code>&gt;<\/code> in <code>Less<\/code>. Now the bigger score counts as &#8220;first&#8221;, so it rises to the top. Everything else stays exactly the same.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: A Priority Queue of Tasks<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ Task is one job with a priority.\ntype Task struct {\n    Name     string\n    Priority int \/\/ a higher number means more urgent\n    index    int \/\/ position in the heap, needed by heap.Fix\n}\n\n\/\/ PriorityQueue keeps the most urgent task on top.\ntype PriorityQueue []*Task\n\nfunc (queue PriorityQueue) Len() int { return len(queue) }\nfunc (queue PriorityQueue) Less(i, j int) bool {\n    return queue[i].Priority &gt; queue[j].Priority \/\/ higher priority comes first\n}\nfunc (queue PriorityQueue) Swap(i, j int) {\n    queue[i], queue[j] = queue[j], queue[i]\n    queue[i].index = i \/\/ keep each task's index up to date\n    queue[j].index = j\n}\nfunc (queue *PriorityQueue) Push(item any) {\n    task := item.(*Task)\n    task.index = len(*queue)\n    *queue = append(*queue, task)\n}\nfunc (queue *PriorityQueue) Pop() any {\n    old := *queue\n    task := old[len(old)-1]\n    old[len(old)-1] = nil \/\/ let the garbage collector free it\n    *queue = old[:len(old)-1]\n    return task\n}\n\nfunc main() {\n    queue := &amp;PriorityQueue{}\n    backup := &amp;Task{Name: \"nightly backup\", Priority: 1}\n    heap.Push(queue, &amp;Task{Name: \"send invoice\", Priority: 3})\n    heap.Push(queue, backup)\n    heap.Push(queue, &amp;Task{Name: \"fix login bug\", Priority: 5})\n\n    backup.Priority = 9          \/\/ the backup became urgent\n    heap.Fix(queue, backup.index) \/\/ move it to its new place in O(log n)\n\n    for queue.Len() &gt; 0 {\n        task := heap.Pop(queue).(*Task) \/\/ .(*Task) turns the any value back into a task\n        fmt.Println(task.Priority, task.Name)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>9 nightly backup\n5 fix login bug\n3 send invoice<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Tasks go in with <code>heap.Push<\/code>, and the most urgent one always comes out first. Each task also stores its own <code>index<\/code>, and <code>Swap<\/code> keeps it correct. That is how <code>heap.Fix<\/code> finds the backup task after its priority changes, without searching the whole slice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Go Heap Programs from Scratch<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Find Parent and Child Positions<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ A min heap stored level by level in a slice.\n    numbers := []int{1, 3, 9, 7, 5}\n\n    for i := range numbers { \/\/ i is each position: 0, 1, 2, ...\n        left := 2*i + 1  \/\/ position of the left child\n        right := 2*i + 2 \/\/ position of the right child\n        fmt.Print(\"index \", i, \" value \", numbers[i])\n        if left &lt; len(numbers) {\n            fmt.Print(\" | left child \", numbers[left])\n        }\n        if right &lt; len(numbers) {\n            fmt.Print(\" | right child \", numbers[right])\n        }\n        if i &gt; 0 {\n            parent := (i - 1) \/ 2 \/\/ whole number division drops the remainder\n            fmt.Print(\" | parent \", numbers[parent])\n        }\n        fmt.Println()\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>index 0 value 1 | left child 3 | right child 9\nindex 1 value 3 | left child 7 | right child 5 | parent 1\nindex 2 value 9 | parent 1\nindex 3 value 7 | parent 3\nindex 4 value 5 | parent 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This program shows the tree hiding inside the slice. For each position, you compute the children with <code>2*i + 1<\/code> and <code>2*i + 2<\/code>, and the parent with <code>(i - 1) \/ 2<\/code>. A child only exists if its position is still inside the slice.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: Check if a Slice is a Min Heap<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ isMinHeap checks that every parent is smaller than or equal to its children.\nfunc isMinHeap(numbers []int) bool {\n    for child := 1; child &lt; len(numbers); child++ {\n        parent := (child - 1) \/ 2\n        if numbers[parent] &gt; numbers[child] {\n            return false \/\/ this parent is bigger than its child\n        }\n    }\n    return true \/\/ every parent passed the test\n}\n\nfunc main() {\n    fmt.Println(isMinHeap([]int{1, 3, 9, 7, 5}))\n    fmt.Println(isMinHeap([]int{1, 2, 3, 4, 5})) \/\/ a sorted slice is always a heap\n    fmt.Println(isMinHeap([]int{4, 1, 3}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>true\ntrue\nfalse<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: Build a Min Heap by Hand<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ MinHeap keeps the smallest value at index 0 of its slice.\ntype MinHeap struct {\n    items []int\n}\n\n\/\/ Push adds at the end, then swaps with the parent while it is smaller.\nfunc (minHeap *MinHeap) Push(value int) {\n    items := append(minHeap.items, value)\n    child := len(items) - 1 \/\/ the new item starts at the end\n    for child &gt; 0 {\n        parent := (child - 1) \/ 2\n        if items[parent] &lt;= items[child] {\n            break \/\/ the order is correct, so stop\n        }\n        items[parent], items[child] = items[child], items[parent] \/\/ swap\n        child = parent                                            \/\/ keep moving up\n    }\n    minHeap.items = items\n}\n\n\/\/ Pop takes the root, moves the last item to the top, then sinks it down.\nfunc (minHeap *MinHeap) Pop() int {\n    items := minHeap.items\n    top := items[0]\n    lastIndex := len(items) - 1\n    items[0] = items[lastIndex] \/\/ Step 1: move the last item to the top\n    items = items[:lastIndex]   \/\/ Step 2: shrink the slice\n    current := 0\n    for { \/\/ Step 3: sink the top item until both children are bigger\n        smallest := current\n        left := 2*current + 1\n        right := 2*current + 2\n        if left &lt; len(items) &amp;&amp; items[left] &lt; items[smallest] {\n            smallest = left\n        }\n        if right &lt; len(items) &amp;&amp; items[right] &lt; items[smallest] {\n            smallest = right\n        }\n        if smallest == current {\n            break \/\/ both children are bigger, so stop\n        }\n        items[current], items[smallest] = items[smallest], items[current]\n        current = smallest\n    }\n    minHeap.items = items\n    return top\n}\n\nfunc main() {\n    var minHeap MinHeap\n    for _, value := range []int{7, 3, 9, 1, 5} {\n        minHeap.Push(value)\n    }\n    fmt.Println(\"slice:\", minHeap.items)\n    for len(minHeap.items) &gt; 0 {\n        fmt.Print(minHeap.Pop(), \" \")\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>slice: [1 3 9 7 5]\n1 3 5 7 9<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Push<\/code> adds the value at the end and swaps it up while its parent is bigger. <code>Pop<\/code> saves the root, moves the last item to the top and swaps it down with its smaller child. The slice <code>[1 3 9 7 5]<\/code> is not sorted, but every parent is smaller than its children. That is all a heap promises.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-1024x640.png\" alt=\"Go heap programs push and pop steps showing sift up and sift down\" class=\"wp-image-849\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Push adds at the end and moves up; pop moves the last item to the root and sinks it down.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Heap Sort<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ sink moves the item at index down inside a max heap of the first size items.\nfunc sink(numbers []int, index, size int) {\n    for {\n        largest := index\n        left := 2*index + 1\n        right := 2*index + 2\n        if left &lt; size &amp;&amp; numbers[left] &gt; numbers[largest] {\n            largest = left\n        }\n        if right &lt; size &amp;&amp; numbers[right] &gt; numbers[largest] {\n            largest = right\n        }\n        if largest == index {\n            return \/\/ both children are smaller, so stop\n        }\n        numbers[index], numbers[largest] = numbers[largest], numbers[index]\n        index = largest\n    }\n}\n\n\/\/ heapSort sorts the slice from small to big, in place.\nfunc heapSort(numbers []int) {\n    size := len(numbers)\n    \/\/ Step 1: build a max heap from the bottom up.\n    for i := size\/2 - 1; i &gt;= 0; i-- {\n        sink(numbers, i, size)\n    }\n    \/\/ Step 2: move the max to the end, then shrink the heap by one.\n    for end := size - 1; end &gt; 0; end-- {\n        numbers[0], numbers[end] = numbers[end], numbers[0]\n        sink(numbers, 0, end)\n    }\n}\n\nfunc main() {\n    numbers := []int{12, 3, 17, 8, 34, 25, 1}\n    heapSort(numbers)\n    fmt.Println(numbers)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 3 8 12 17 25 34]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go Heap Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go heap programs solve the top K and merging questions that appear in most coding rounds.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: Kth Largest Element<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ IntHeap is a min heap of numbers (the five methods from Program 1).\ntype IntHeap []int\n\nfunc (numbers IntHeap) Len() int           { return len(numbers) }\nfunc (numbers IntHeap) Less(i, j int) bool { return numbers[i] &lt; numbers[j] }\nfunc (numbers IntHeap) Swap(i, j int)      { numbers[i], numbers[j] = numbers[j], numbers[i] }\nfunc (numbers *IntHeap) Push(item any)     { *numbers = append(*numbers, item.(int)) }\nfunc (numbers *IntHeap) Pop() any {\n    old := *numbers\n    last := old[len(old)-1]\n    *numbers = old[:len(old)-1]\n    return last\n}\n\n\/\/ kthLargest keeps a min heap of the kth biggest values seen so far.\n\/\/ The smallest of those values is the answer.\nfunc kthLargest(numbers []int, kth int) int {\n    best := &amp;IntHeap{}\n    for _, value := range numbers {\n        heap.Push(best, value)\n        if best.Len() &gt; kth {\n            heap.Pop(best) \/\/ drop the smallest, keep only kth items\n        }\n    }\n    return (*best)[0]\n}\n\nfunc main() {\n    fmt.Println(kthLargest([]int{3, 2, 1, 5, 6, 4}, 2))\n    fmt.Println(kthLargest([]int{3, 2, 3, 1, 2, 4, 5, 5, 6}, 4))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>5\n4<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The heap <code>best<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: Top K Frequent Words<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ wordCount pairs a word with how many times it appears.\ntype wordCount struct {\n    word  string\n    count int\n}\n\n\/\/ countHeap is a min heap: the \"weakest\" word is on top, so we can drop it.\ntype countHeap []wordCount\n\nfunc (entries countHeap) Len() int { return len(entries) }\nfunc (entries countHeap) Less(i, j int) bool {\n    if entries[i].count != entries[j].count {\n        return entries[i].count &lt; entries[j].count\n    }\n    return entries[i].word &gt; entries[j].word \/\/ on a tie, the later word is weaker\n}\nfunc (entries countHeap) Swap(i, j int)  { entries[i], entries[j] = entries[j], entries[i] }\nfunc (entries *countHeap) Push(item any) { *entries = append(*entries, item.(wordCount)) }\nfunc (entries *countHeap) Pop() any {\n    old := *entries\n    last := old[len(old)-1]\n    *entries = old[:len(old)-1]\n    return last\n}\n\n\/\/ topK returns the howMany most frequent words, most frequent first.\nfunc topK(text string, howMany int) []string {\n    counts := map[string]int{}\n    for _, word := range strings.Fields(text) { \/\/ Fields splits the text at spaces\n        counts[word]++\n    }\n    strongest := &amp;countHeap{}\n    for word, count := range counts {\n        heap.Push(strongest, wordCount{word: word, count: count})\n        if strongest.Len() &gt; howMany {\n            heap.Pop(strongest) \/\/ drop the weakest word\n        }\n    }\n    result := make([]string, strongest.Len())\n    for i := len(result) - 1; i &gt;= 0; i-- { \/\/ pop weakest first, fill from the back\n        result[i] = heap.Pop(strongest).(wordCount).word\n    }\n    return result\n}\n\nfunc main() {\n    fmt.Println(topK(\"go is fun go is fast go rocks\", 2))\n    fmt.Println(topK(\"b a c a b c d\", 3))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[go is]\n[a b c]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>word<\/code> makes the answer the same on every run, even though map order is random.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Merge K Sorted Slices<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ entry remembers a value, which list it came from and its position there.\ntype entry struct {\n    value     int\n    listIndex int\n    position  int\n}\n\n\/\/ entryHeap is a min heap ordered by value.\ntype entryHeap []entry\n\nfunc (entries entryHeap) Len() int           { return len(entries) }\nfunc (entries entryHeap) Less(i, j int) bool { return entries[i].value &lt; entries[j].value }\nfunc (entries entryHeap) Swap(i, j int)      { entries[i], entries[j] = entries[j], entries[i] }\nfunc (entries *entryHeap) Push(item any)     { *entries = append(*entries, item.(entry)) }\nfunc (entries *entryHeap) Pop() any {\n    old := *entries\n    last := old[len(old)-1]\n    *entries = old[:len(old)-1]\n    return last\n}\n\n\/\/ mergeK joins many sorted slices into one sorted slice.\nfunc mergeK(lists [][]int) []int {\n    fronts := &amp;entryHeap{}\n    \/\/ Step 1: push the first item of each list.\n    for i, list := range lists {\n        if len(list) &gt; 0 {\n            heap.Push(fronts, entry{value: list[0], listIndex: i, position: 0})\n        }\n    }\n    \/\/ Step 2: pop the smallest, then push the next item from the same list.\n    var merged []int\n    for fronts.Len() &gt; 0 {\n        smallest := heap.Pop(fronts).(entry)\n        merged = append(merged, smallest.value)\n        nextPosition := smallest.position + 1\n        list := lists[smallest.listIndex]\n        if nextPosition &lt; len(list) {\n            heap.Push(fronts, entry{value: list[nextPosition], listIndex: smallest.listIndex, position: nextPosition})\n        }\n    }\n    return merged\n}\n\nfunc main() {\n    fmt.Println(mergeK([][]int{{1, 4, 9}, {2, 3, 10}, {5, 6}}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 2 3 4 5 6 9 10]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: Running Median with Two Heaps<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ NumberHeap is a min heap, or a max heap when isMax is true.\ntype NumberHeap struct {\n    items []int\n    isMax bool \/\/ true: biggest on top, false: smallest on top\n}\n\nfunc (half NumberHeap) Len() int { return len(half.items) }\nfunc (half NumberHeap) Less(i, j int) bool {\n    if half.isMax {\n        return half.items[i] &gt; half.items[j]\n    }\n    return half.items[i] &lt; half.items[j]\n}\nfunc (half NumberHeap) Swap(i, j int)      { half.items[i], half.items[j] = half.items[j], half.items[i] }\nfunc (half *NumberHeap) Push(item any)     { half.items = append(half.items, item.(int)) }\nfunc (half *NumberHeap) Pop() any {\n    last := half.items[len(half.items)-1]\n    half.items = half.items[:len(half.items)-1]\n    return last\n}\n\nfunc main() {\n    low := &amp;NumberHeap{isMax: true} \/\/ smaller half, biggest on top\n    high := &amp;NumberHeap{}           \/\/ bigger half, smallest on top\n    for _, value := range []int{5, 15, 1, 3, 8} {\n        \/\/ Step 1: add to the low half, then move its biggest to the high half.\n        heap.Push(low, value)\n        heap.Push(high, heap.Pop(low))\n        \/\/ Step 2: keep low the same size as high, or one bigger.\n        if high.Len() &gt; low.Len() {\n            heap.Push(low, heap.Pop(high))\n        }\n        \/\/ Step 3: read the median from the two tops.\n        if low.Len() &gt; high.Len() {\n            fmt.Printf(\"add %d -&gt; median %d\\n\", value, low.items[0])\n        } else {\n            median := float64(low.items[0]+high.items[0]) \/ 2 \/\/ float64 keeps the .5\n            fmt.Printf(\"add %d -&gt; median %.1f\\n\", value, median) \/\/ %.1f prints one decimal place\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>add 5 -&gt; median 5\nadd 15 -&gt; median 10.0\nadd 1 -&gt; median 5\nadd 3 -&gt; median 4.0\nadd 8 -&gt; median 5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>low<\/code> heap holds the smaller half of the numbers, with its biggest on top. The <code>high<\/code> 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 <code>isMax<\/code> field lets the same type work as a min heap or a max heap.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: K Closest Points to the Origin<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n    \"slices\"\n)\n\n\/\/ Point is a spot on a map. x and y are the usual names for its two coordinates.\ntype Point struct{ x, y int }\n\n\/\/ squaredDistance measures how far a point is from (0, 0). No square root is needed to compare.\nfunc squaredDistance(point Point) int { return point.x*point.x + point.y*point.y }\n\n\/\/ farHeap is a max heap by distance, so the farthest point is dropped first.\ntype farHeap []Point\n\nfunc (points farHeap) Len() int { return len(points) }\nfunc (points farHeap) Less(i, j int) bool {\n    return squaredDistance(points[i]) &gt; squaredDistance(points[j])\n}\nfunc (points farHeap) Swap(i, j int)  { points[i], points[j] = points[j], points[i] }\nfunc (points *farHeap) Push(item any) { *points = append(*points, item.(Point)) }\nfunc (points *farHeap) Pop() any {\n    old := *points\n    last := old[len(old)-1]\n    *points = old[:len(old)-1]\n    return last\n}\n\n\/\/ byDistance compares two points for sorting, nearest first.\nfunc byDistance(first, second Point) int {\n    return squaredDistance(first) - squaredDistance(second)\n}\n\nfunc main() {\n    drivers := []Point{{3, 3}, {5, -1}, {-2, 4}, {1, 1}, {0, 2}}\n    closest := &amp;farHeap{}\n    for _, driver := range drivers {\n        heap.Push(closest, driver)\n        if closest.Len() &gt; 3 {\n            heap.Pop(closest) \/\/ drop the farthest, keep the 3 nearest\n        }\n    }\n    nearest := []Point(*closest) \/\/ turn the heap back into a plain slice\n    slices.SortFunc(nearest, byDistance) \/\/ nearest first for printing\n    fmt.Println(nearest)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[{1 1} {0 2} {3 3}]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>math.Sqrt<\/code> calls. Ride apps use this idea to find the nearest drivers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Minimum Meeting Rooms<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n    \"slices\"\n)\n\n\/\/ IntHeap is a min heap of numbers (the five methods from Program 1).\ntype IntHeap []int\n\nfunc (numbers IntHeap) Len() int           { return len(numbers) }\nfunc (numbers IntHeap) Less(i, j int) bool { return numbers[i] &lt; numbers[j] }\nfunc (numbers IntHeap) Swap(i, j int)      { numbers[i], numbers[j] = numbers[j], numbers[i] }\nfunc (numbers *IntHeap) Push(item any)     { *numbers = append(*numbers, item.(int)) }\nfunc (numbers *IntHeap) Pop() any {\n    old := *numbers\n    last := old[len(old)-1]\n    *numbers = old[:len(old)-1]\n    return last\n}\n\n\/\/ byStart compares two meetings by start time, for sorting.\nfunc byStart(first, second [2]int) int { return first[0] - second[0] }\n\n\/\/ minRooms sorts meetings by start time and keeps a heap of end times.\n\/\/ Each meeting is [2]int: index 0 is the start, index 1 is the end.\nfunc minRooms(meetings [][2]int) int {\n    slices.SortFunc(meetings, byStart)\n    endTimes := &amp;IntHeap{}\n    for _, meeting := range meetings {\n        start := meeting[0]\n        end := meeting[1]\n        if endTimes.Len() &gt; 0 &amp;&amp; (*endTimes)[0] &lt;= start {\n            heap.Pop(endTimes) \/\/ the earliest room is free again, so reuse it\n        }\n        heap.Push(endTimes, end)\n    }\n    return endTimes.Len() \/\/ rooms still in use at the busiest time\n}\n\nfunc main() {\n    fmt.Println(minRooms([][2]int{{9, 10}, {9, 12}, {10, 11}, {11, 13}}))\n    fmt.Println(minRooms([][2]int{{9, 10}, {10, 11}}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2\n1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: A Generic Heap with cmp.Ordered<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"fmt\"\n)\n\n\/\/ Heap[T] is a min heap for any ordered type T, with no interface methods.\ntype Heap[T cmp.Ordered] struct {\n    items []T\n}\n\n\/\/ Push adds at the end, then moves the value up while it is smaller than its parent.\nfunc (minHeap *Heap[T]) Push(value T) {\n    items := append(minHeap.items, value)\n    child := len(items) - 1\n    for child &gt; 0 {\n        parent := (child - 1) \/ 2\n        if items[parent] &lt;= items[child] {\n            break\n        }\n        items[parent], items[child] = items[child], items[parent]\n        child = parent\n    }\n    minHeap.items = items\n}\n\n\/\/ Pop removes the smallest value and sinks the new top down.\nfunc (minHeap *Heap[T]) Pop() T {\n    items := minHeap.items\n    top := items[0]\n    lastIndex := len(items) - 1\n    items[0] = items[lastIndex]\n    items = items[:lastIndex]\n    current := 0\n    for {\n        smallest := current\n        left := 2*current + 1\n        right := 2*current + 2\n        if left &lt; len(items) &amp;&amp; items[left] &lt; items[smallest] {\n            smallest = left\n        }\n        if right &lt; len(items) &amp;&amp; items[right] &lt; items[smallest] {\n            smallest = right\n        }\n        if smallest == current {\n            break\n        }\n        items[current], items[smallest] = items[smallest], items[current]\n        current = smallest\n    }\n    minHeap.items = items\n    return top\n}\n\nfunc main() {\n    var words Heap[string] \/\/ T is string here\n    for _, word := range []string{\"pear\", \"apple\", \"mango\", \"fig\"} {\n        words.Push(word)\n    }\n    for len(words.items) &gt; 0 {\n        fmt.Print(words.Pop(), \" \")\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>apple fig mango pear<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is the hand-made heap from Program 6, but with a type parameter <code>T<\/code>. The rule <code>cmp.Ordered<\/code> means <code>T<\/code> must support <code>&lt;<\/code>, so it works for ints, floats and strings without any <code>any<\/code> conversions. See our generics post for more on <code>cmp.Ordered<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Heap vs Sorted Slice in Go Heap Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both can give you the smallest item, but they cost very different amounts as items arrive. The table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Heap<\/th><th>Sorted slice<\/th><\/tr><\/thead><tbody><tr><td>Get the smallest<\/td><td>O(1)<\/td><td>O(1)<\/td><\/tr><tr><td>Add one item<\/td><td>O(log n)<\/td><td>O(n), shifts items<\/td><\/tr><tr><td>Remove the smallest<\/td><td>O(log n)<\/td><td>O(n) from the front<\/td><\/tr><tr><td>Fully sorted<\/td><td>No, only the top is known<\/td><td>Yes<\/td><\/tr><tr><td>Best for<\/td><td>Items keep arriving<\/td><td>Data that rarely changes<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Heap Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Calling numbers.Push instead of heap.Push:<\/strong> your method only appends and breaks the heap order.<\/li>\n\n\n<li><strong>Value receivers on Push and Pop:<\/strong> they must be pointer receivers to change the length.<\/li>\n\n\n<li><strong>Forgetting heap.Init:<\/strong> a slice you fill directly is not a heap until you call it.<\/li>\n\n\n<li><strong>Reading the last item as the max:<\/strong> only index 0 is known, the rest is not sorted.<\/li>\n\n\n<li><strong>No tie-breaker:<\/strong> equal priorities can come out in any order without one.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Heap Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Keep the heap size at k<\/strong> for top K problems, so the cost is O(n log k).<\/li>\n\n\n<li><strong>Store an index field<\/strong> when you need <code>heap.Fix<\/code> or <code>heap.Remove<\/code>.<\/li>\n\n\n<li><strong>Set popped pointer slots to nil<\/strong> so the garbage collector can free them.<\/li>\n\n\n<li><strong>Use a min heap for &#8220;largest k&#8221;<\/strong> and a max heap for &#8220;smallest k&#8221;.<\/li>\n\n\n<li><strong>Write a generic heap<\/strong> when you use the same pattern for many types.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Heap Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Concept Questions on Go Heap Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. Which five methods does heap.Interface need?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Len<\/code>, <code>Less<\/code> and <code>Swap<\/code> come from <code>sort.Interface<\/code>, plus <code>Push(item any)<\/code> and <code>Pop() any<\/code>. The package calls them for you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. Is a heap the same as a sorted array?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. A heap only promises that each parent beats its children. The slice <code>[1 3 9 7 5]<\/code> is a valid min heap but is not sorted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n    \"sort\"\n)\n\n\/\/ NumberHeap embeds sort.IntSlice, which already has Len, Less and Swap.\n\/\/ So we only add Push and Pop.\ntype NumberHeap struct{ sort.IntSlice }\n\nfunc (numbers *NumberHeap) Push(item any) {\n    numbers.IntSlice = append(numbers.IntSlice, item.(int))\n}\nfunc (numbers *NumberHeap) Pop() any {\n    old := numbers.IntSlice\n    last := old[len(old)-1]\n    numbers.IntSlice = old[:len(old)-1]\n    return last\n}\n\nfunc main() {\n    numbers := &amp;NumberHeap{sort.IntSlice{4, 1, 3}}\n    heap.Init(numbers)\n    heap.Push(numbers, 2)\n    fmt.Println(heap.Pop(numbers), heap.Pop(numbers), numbers.Len())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 2 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Embedding <code>sort.IntSlice<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. What is the time to build a heap from n items?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>heap.Init<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Coding Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. How do you sort strings by length with a heap?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\n\/\/ ByLength is a min heap of words: shorter words come out first.\ntype ByLength []string\n\nfunc (words ByLength) Len() int { return len(words) }\nfunc (words ByLength) Less(i, j int) bool {\n    if len(words[i]) != len(words[j]) {\n        return len(words[i]) &lt; len(words[j]) \/\/ shorter first\n    }\n    return words[i] &lt; words[j] \/\/ same length: alphabetical\n}\nfunc (words ByLength) Swap(i, j int)  { words[i], words[j] = words[j], words[i] }\nfunc (words *ByLength) Push(item any) { *words = append(*words, item.(string)) }\nfunc (words *ByLength) Pop() any {\n    old := *words\n    last := old[len(old)-1]\n    *words = old[:len(old)-1]\n    return last\n}\n\nfunc main() {\n    fruits := &amp;ByLength{\"banana\", \"kiwi\", \"fig\", \"apple\", \"pear\"}\n    heap.Init(fruits)\n    for fruits.Len() &gt; 0 {\n        fmt.Print(heap.Pop(fruits), \" \")\n    }\n    fmt.Println()\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>fig kiwi pear apple banana<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">All the ordering rules live in <code>Less<\/code>. Here it compares lengths first and uses the alphabet only on a tie. Change that one method, and the heap order changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What happens if you call heap.Pop on an empty heap?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"container\/heap\"\n    \"sort\"\n)\n\n\/\/ NumberHeap embeds sort.IntSlice and adds Push and Pop.\ntype NumberHeap struct{ sort.IntSlice }\n\nfunc (numbers *NumberHeap) Push(item any) {\n    numbers.IntSlice = append(numbers.IntSlice, item.(int))\n}\nfunc (numbers *NumberHeap) Pop() any {\n    old := numbers.IntSlice\n    last := old[len(old)-1]\n    numbers.IntSlice = old[:len(old)-1]\n    return last\n}\n\nfunc main() {\n    numbers := &amp;NumberHeap{}\n    heap.Pop(numbers) \/\/ nothing to pop, so this panics\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>panic: runtime error: index out of range<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>heap.Pop<\/code> does not check the length for you. Always test <code>numbers.Len() &gt; 0<\/code> before popping.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How do you remove any item from the middle of a heap?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep the item&#8217;s index, as in Program 3, and call <code>heap.Remove(queue, index)<\/code>. It swaps the item with the last one, removes it and then fixes the order in O(log n).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Design Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. How would you find the top 10 search terms from a log of one billion lines?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. When is sorting better than a heap?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When you need all items in order once and no new items arrive. <code>slices.Sort<\/code> is simple and very fast for that case.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. How does Go&#8217;s timer system relate to heaps?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go heap programs, write a task scheduler that reads jobs as <code>name priority<\/code> lines, such as <code>deploy 5<\/code>, <code>email 1<\/code> and <code>backup 3<\/code>. Print them in priority order, highest first, with equal priorities in alphabetical order. Hint: put the tie rule inside <code>Less<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/container\/heap\">container\/heap package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/sort\">sort package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/cmp\">cmp package documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go heap programs keep the smallest or biggest item at index 0 of a slice.<\/li>\n\n\n<li>Push and pop cost O(log n), and looking at the top costs O(1).<\/li>\n\n\n<li><code>container\/heap<\/code> needs Len, Less, Swap, Push and Pop.<\/li>\n\n\n<li>A heap of size k solves top K problems in O(n log k).<\/li>\n\n\n<li>Two heaps give a running median, and an index field enables heap.Fix.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we build trees where every node can have children on both sides. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-tree-programs\/\">Go tree programs<\/a>, with binary search trees, traversals, height and lowest common ancestor. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-stack-and-queue-programs\/\">Go stack and queue programs<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go heap programs give you the smallest or biggest item in a collection instantly, even while items keep arriving. In this post, you will&hellip;<\/p>\n","protected":false},"author":1,"featured_media":847,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,121,95,11,104],"swapz_series":[],"class_list":["post-850","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-heap","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Heap Programs: Priority Queue, Top K, Median<\/title>\n<meta name=\"description\" content=\"Go heap programs with output: container\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-heap-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Heap Programs: Priority Queue, Top K, Median\" \/>\n<meta property=\"og:description\" content=\"Go heap programs with output: container\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-heap-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-10T07:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"26 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Heap Programs: Priority Queue, Top K and Running Median\",\"datePublished\":\"2026-10-10T07:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:25+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/\"},\"wordCount\":2046,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-heap-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Heap\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/\",\"name\":\"Go Heap Programs: Priority Queue, Top K, Median\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-heap-programs-featured.png\",\"datePublished\":\"2026-10-10T07:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:25+00:00\",\"description\":\"Go heap programs with output: container\\\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-heap-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-heap-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Heap Programs featured image: priority queue and top K output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-heap-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Heap Programs: Priority Queue, Top K and Running Median\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Heap Programs: Priority Queue, Top K, Median","description":"Go heap programs with output: container\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&A.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Heap Programs: Priority Queue, Top K, Median","og_description":"Go heap programs with output: container\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-10T07:30:00+00:00","article_modified_time":"2026-11-28T19:59:25+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"26 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Heap Programs: Priority Queue, Top K and Running Median","datePublished":"2026-10-10T07:30:00+00:00","dateModified":"2026-11-28T19:59:25+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/"},"wordCount":2046,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png","keywords":["Beginner","Go Heap","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/","name":"Go Heap Programs: Priority Queue, Top K, Median","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png","datePublished":"2026-10-10T07:30:00+00:00","dateModified":"2026-11-28T19:59:25+00:00","description":"Go heap programs with output: container\/heap, a heap from scratch, heap sort, Kth largest, top K words, merge K lists and a median, plus interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-heap-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-heap-programs-featured.png","width":2400,"height":1260,"caption":"Go Heap Programs featured image: priority queue and top K output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-heap-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Heap Programs: Priority Queue, Top K and Running Median"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/850","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=850"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/850\/revisions"}],"predecessor-version":[{"id":901,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/850\/revisions\/901"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/847"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=850"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=850"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=850"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=850"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}