Sub topic 9
Why the Greedy Choice Is Optimal
This chapter assumes you can already build a Huffman tree with a min-heap, compute a code's average length, and follow a proof by induction. It covers one question: why does always merging the two least frequent nodes give the best possible prefix code?
What "optimal" means here
The cost of a code tree is its weighted path length. You multiply each symbol's frequency by its depth in the tree (its code length) and add up the results:
cost(T) = Σ f(s) · depth(s)
This sum is the total number of bits in the encoded message. Huffman's claim is narrow. No other prefix code that assigns a fixed bit string to each symbol produces a smaller total. The claim says nothing about schemes that code groups of symbols together or that use fractional bits.
Three facts that make the proof work
Fact 1: optimal trees are full
In a full tree, every internal node has two children. Suppose an internal node has only one child. You can remove that node and pull its subtree up one level. Every code below it gets one bit shorter and the code stays prefix-free. So an optimal tree never contains a one-child node.
Fact 2: the two rarest symbols can be deepest siblings
Let x and y be the two least frequent symbols. In a full tree, the deepest leaf always has a sibling that is also a leaf. Take that pair of deepest leaves and swap x and y into their positions. Moving a low-frequency symbol deeper and a higher-frequency symbol shallower never raises the cost. For one swap, the change is (f(a) − f(x)) · (depth(x) − depth(a)) ≤ 0. So some optimal tree has x and y as siblings at the maximum depth. That is the pair Huffman merges first.
Fact 3: merging reduces the problem exactly
Replace x and y with a single symbol z where f(z) = f(x) + f(y). Call the smaller tree T′. Splitting z back into x and y adds one bit to each of their codes, so:
cost(T) = cost(T′) + f(x) + f(y)
The extra term f(x) + f(y) is the same whichever tree you choose for the reduced problem. Minimizing cost(T′) therefore minimizes cost(T).
The induction
With one symbol, the cost is zero, so any tree is optimal. For n symbols, Fact 2 says some optimal tree pairs x and y. Fact 3 says that tree's cost equals the cost of an optimal (n−1)-symbol tree plus a constant. Huffman builds exactly that tree.
Checking it by brute force
Fact 3 implies that a tree's cost equals the sum of the weights created at each merge. Every full tree can be built by some sequence of pairwise merges. So trying every merge order explores every possible prefix code.
import heapq
import random
from functools import lru_cache
def huffman_cost(freqs):
heap = list(freqs)
heapq.heapify(heap)
total = 0
while len(heap) > 1:
a = heapq.heappop(heap)
b = heapq.heappop(heap)
total += a + b
heapq.heappush(heap, a + b)
return total
@lru_cache(maxsize=None)
def best_cost(freqs):
# freqs: sorted tuple; tries every possible pair to merge
if len(freqs) <= 1:
return 0
best = None
for i in range(len(freqs)):
for j in range(i + 1, len(freqs)):
rest = [f for k, f in enumerate(freqs) if k not in (i, j)]
merged = freqs[i] + freqs[j]
cost = merged + best_cost(tuple(sorted(rest + [merged])))
if best is None or cost < best:
best = cost
return best
print(huffman_cost([5, 2, 2, 1, 1])) # abracadabra: 23 bits
for _ in range(200):
fs = tuple(sorted(random.randint(1, 20) for _ in range(random.randint(2, 6))))
assert huffman_cost(fs) == best_cost(fs)
print("Huffman matched the exhaustive optimum on all trials")Exercise
A student proposes merging the two MOST frequent nodes at each step. For frequencies 5, 2, 2, 1, 1, compute the cost of this strategy and explain which fact in the proof it violates.
Show answer
The merges are 5+2=7, 7+2=9, 9+1=10, 10+1=11, so the total is 7+9+10+11 = 37 bits, compared with Huffman's 23. This strategy puts the most frequent symbols deepest in the tree, which breaks Fact 2. Swapping a deep frequent symbol with a shallow rare one would lower the cost.
Exercise
Why does the proof need the extra cost f(x) + f(y) to be independent of how the reduced tree T′ is shaped?
Show answer
Because then cost(T) and cost(T′) differ by a constant. Any tree that minimizes cost(T′) also minimizes cost(T). If the extra term depended on T′, an optimal reduced tree might not give an optimal full tree.