Huffman Coding visualization

Build an optimal prefix code by repeatedly merging the two least frequent symbols.

Put every symbol in a min-priority queue by frequency. Pop the two smallest, merge them under a new parent whose weight is their sum, push it back. The last node is the root.

Left edges are 0, right edges are 1: frequent symbols end up near the root with short codes. Edge case: a text with one distinct symbol still needs a 1-bit code.

Complexity

Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(n). Difficulty: Advanced.

Pseudocode

procedure huffman(text):
  count frequency of each symbol
  pq ← min-heap of leaves by frequency
  while |pq| > 1:
    a ← pq.pop(); b ← pq.pop()
    pq.push(node(a.w + b.w, left=a, right=b))
  assign codes: left = 0, right = 1

More greedy algorithms