Huffman Coding Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Huffman Coding runs in O(n log n) time and O(n) space, in Go as in every other language.
- ✓container/heap is an interface, not a container. You implement Len, Less and Swap from sort.Interface, add Push(any) and Pop() any, and then hand your value to heap.Init, heap.Push and heap.Pop.
- ✓Push and Pop take pointer receivers, because both change the length of the slice and a value receiver would append into a copy that is thrown away.
- ✓The Go trap: Your type has a Pop method and the package has a Pop function, and they do opposite things.
- ✓Every heap.Push and heap.Pop passes through any. Storing *node keeps that free, because a pointer goes straight into the interface's data word; storing a node by value would make the runtime allocate a copy on each push.
What Huffman Coding actually is
Huffman Coding in Go: what you actually reach for
Go implementation
package main
import "container/heap"
import "fmt"
// Weather phenomenon codes tallied from one station's METAR log.
type node struct{ code string; w, seq int; lo, hi *node }
type pq []*node
func (p pq) Len() int { return len(p) }
func (p pq) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p pq) Less(i, j int) bool {
return p[i].w < p[j].w || (p[i].w == p[j].w && p[i].seq < p[j].seq)
}
// Push and Pop take pointer receivers: both resize the slice header.
func (p *pq) Push(x any) { *p = append(*p, x.(*node)) }
func (p *pq) Pop() any {
old := *p
tail := old[len(old)-1]
old[len(old)-1], *p = nil, old[:len(old)-1] // drop the ref, keep it collectable
return tail
}
func walk(n *node, d int) {
if n.lo == nil {
fmt.Printf("%s=%d ", n.code, max(d, 1)) // max covers a 1-symbol alphabet
return
}
walk(n.lo, d+1)
walk(n.hi, d+1)
}
func main() {
h := pq{{code: "RA", w: 5120, seq: 0}, {code: "BR", w: 1810, seq: 1},
{code: "SN", w: 640, seq: 2}, {code: "FG", w: 210, seq: 3},
{code: "TS", w: 44, seq: 4}, {code: "GR", w: 3, seq: 5}}
heap.Init(&h) // O(n) heapify; n separate heap.Push calls would be O(n log n)
for seq := h.Len(); h.Len() > 1; seq++ {
lo, hi := heap.Pop(&h).(*node), heap.Pop(&h).(*node) // never h.Pop(): no sift
heap.Push(&h, &node{w: lo.w + hi.w, seq: seq, lo: lo, hi: hi})
}
walk(h[0], 0)
fmt.Println()
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Huffman Coding?
container/heap is an interface, not a container. You implement Len, Less and Swap from sort.Interface, add Push(any) and Pop() any, and then hand your value to heap.Init, heap.Push and heap.Pop. heap.Init runs in O(n). Generics landed in the language, but this package predates them and still traffics in any, so every element crosses an interface boundary and needs a type assertion coming back out. The tally is a plain map[string]int, and sort.Slice or slices.SortFunc orders the output.
What is the most common Go mistake when implementing Huffman Coding?
Your type has a Pop method and the package has a Pop function, and they do opposite things. heap.Pop(h) swaps element 0 to the end, sifts the remaining range down, and only then calls your Pop to strip off the last slot. Call h.Pop() directly and you get element Len()-1 with no sift at all, which in a min-heap is a leaf and usually near the maximum. Initialise a heap over [5120 1810 640 210 44 3] and the array becomes [3 44 640 210 1810 5120]: the minimum is 3 and the bare method hands back 5120. It compiles, the type assertion succeeds, and the tree is quietly wrong.
How does Huffman Coding actually perform in Go?
Every heap.Push and heap.Pop passes through any. Storing *node keeps that free, because a pointer goes straight into the interface's data word; storing a node by value would make the runtime allocate a copy on each push. Less is invoked through the interface on every comparison, so it is a dynamic call the compiler cannot inline, and that is the real constant here. Once the leaves are sorted the two-queue variant drops the heap entirely: merged weights come out non-decreasing, so a second slice and two indices finish in O(n) with no interface traffic left. Time complexity is O(n log n) and space is O(n).
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.