Algorithms · Huffman Coding and Optimal Merge Pattern
Huffman's Algorithm
2.1 The greedy step
Repeatedly take the two nodes of smallest weight and merge them into a new node whose weight is their sum. The two removed nodes become its children.
2.2 Step-by-step method (exam recipe)
- Create a leaf for each symbol with weight . Put all leaves in a min-heap keyed by weight.
- Repeat times:
- Extract-min twice → nodes with weights .
- Create internal node with weight ; make the left child (edge 0) and the right child (edge 1) — the 0/1 assignment is a convention and does not affect cost.
- Insert into the heap.
- The single remaining node is the root. Read codewords off the root-to-leaf paths.
- Total bits ; average length .
2.3 Complexity
Each heap operation is ; there are insertions and extract-mins plus insertions of internal nodes, i.e. heap operations. Total:
If the frequencies are already sorted, a two-queue method (one queue of leaves, one queue of merged nodes, both sorted) gives — a fact GATE has asked about.
2.4 Structural facts
- A full binary tree with leaves has exactly internal nodes and nodes total.
- Hence the Huffman tree for symbols has merges and internal nodes.
- No leaf has depth 0 unless (degenerate case).
- Some optimal tree has the two least frequent symbols as siblings at maximum depth (this is the exchange argument behind optimality; with ties not every optimal tree has this shape).
2.5 Why it is optimal (exchange argument, sketch)
Take any optimal tree . Let be the two least frequent symbols. One can swap them with the two deepest sibling leaves without increasing cost (because exchanging a lighter symbol with a heavier, shallower one never increases : the change is ). So some optimal tree has as deepest siblings. Contracting them into one leaf of weight reduces the problem to symbols, and the cost of the original tree equals the cost of the contracted tree plus . By induction the greedy choice is safe — the greedy-choice and optimal-substructure properties hold, so Huffman is optimal among all prefix codes.