TExcelTAD

Why Huffman Codes Are Optimal

Huffman's algorithm makes one greedy decision over and over: join the two lightest trees. The previous lesson showed that it produces short codes. This lesson proves that no prefix code is shorter, using exactly the two-property recipe of The Greedy-Choice Property and Exchange Arguments: an exchange argument for the greedy choice and a cost identity for optimal substructure. Then it checks the theorem by brute force on random inputs and ends with a linear-time version of the algorithm.

Throughout, CC is the alphabet with frequencies c.freqc.\mathit{freq}, TT a full binary tree whose leaves are the symbols, and B(T)=∑cc.freq⋅dT(c)B(T) = \sum_{c} c.\mathit{freq} \cdot d_T(c) its cost.

Lemma 1: the greedy choice is safe

Lemma 1. Let xx and yy be two symbols of lowest frequency. Then some optimal tree has xx and yy as sibling leaves at the maximum depth, so their codewords have the same length and differ only in the last bit.

Proof. Take any optimal tree TT. Being full, it has two sibling leaves aa and bb at its maximum depth (the deepest leaf's parent has two children, and both must be leaves). Name them so that a.freq≤b.freqa.\mathit{freq} \le b.\mathit{freq}, and name x,yx, y so that x.freq≤y.freqx.\mathit{freq} \le y.\mathit{freq}. Since xx and yy are the two least frequent symbols, x.freq≤a.freqx.\mathit{freq} \le a.\mathit{freq} and y.freq≤b.freqy.\mathit{freq} \le b.\mathit{freq}.

Swap xx and aa in the tree, giving T′T'. Only those two leaves change depth, so

B(T)−B(T′)=x.freq dT(x)+a.freq dT(a)−x.freq dT(a)−a.freq dT(x)=(a.freq−x.freq)(dT(a)−dT(x)) ≥ 0,\begin{aligned} B(T) - B(T') &= x.\mathit{freq}\, d_T(x) + a.\mathit{freq}\, d_T(a) - x.\mathit{freq}\, d_T(a) - a.\mathit{freq}\, d_T(x) \\ &= (a.\mathit{freq} - x.\mathit{freq}) \bigl( d_T(a) - d_T(x) \bigr) \ \ge\ 0, \end{aligned}

because both factors are non-negative: aa is at least as frequent as xx and at maximum depth. So B(T′)≤B(T)B(T') \le B(T). Swap yy and bb the same way to get T′′T'' with B(T′′)≤B(T′)≤B(T)B(T'') \le B(T') \le B(T). Since TT was optimal, T′′T'' is optimal too, and in it xx and yy are siblings at maximum depth. (If xx or yy already coincides with aa or bb, some swaps are unnecessary; the inequalities still hold.) ■\blacksquare

The swap is the whole idea: moving a rarer symbol deeper and a more common one shallower never hurts. It is the rearrangement inequality applied to depths and frequencies.

Lemma 2: optimal substructure

Let x,yx, y be two least frequent symbols. Form the alphabet C′=C∖{x,y}∪{z}C' = C \setminus \{x, y\} \cup \{z\} with a new symbol zz, z.freq=x.freq+y.freqz.\mathit{freq} = x.\mathit{freq} + y.\mathit{freq}. This is exactly what one Huffman merge does.

Lemma 2. If T′T' is an optimal tree for C′C', then the tree TT obtained from T′T' by replacing the leaf zz with an internal node whose children are xx and yy is optimal for CC.

Proof. First the cost relation. Every symbol other than x,yx, y has the same depth in TT and T′T', and dT(x)=dT(y)=dT′(z)+1d_T(x) = d_T(y) = d_{T'}(z) + 1. So

x.freq dT(x)+y.freq dT(y)=z.freq (dT′(z)+1),henceB(T)=B(T′)+x.freq+y.freq.x.\mathit{freq}\, d_T(x) + y.\mathit{freq}\, d_T(y) = z.\mathit{freq}\,\bigl(d_{T'}(z) + 1\bigr), \qquad \text{hence} \qquad B(T) = B(T') + x.\mathit{freq} + y.\mathit{freq}.

Now suppose TT were not optimal: some tree SS for CC has B(S)<B(T)B(S) < B(T). By Lemma 1 we may assume xx and yy are siblings in SS. Replace them and their parent by a single leaf zz, giving a tree S′S' for C′C' with B(S′)=B(S)−x.freq−y.freq<B(T)−x.freq−y.freq=B(T′)B(S') = B(S) - x.\mathit{freq} - y.\mathit{freq} < B(T) - x.\mathit{freq} - y.\mathit{freq} = B(T'), which contradicts the optimality of T′T'. ■\blacksquare

The theorem

Theorem. Huffman's algorithm produces an optimal prefix code.

Proof by induction on n=∣C∣n = \lvert C \rvert. For n=2n = 2 the only full tree has both symbols at depth 1, and Huffman produces it. For n>2n > 2, the algorithm's first step merges two least frequent symbols x,yx, y into zz, and the remaining steps are exactly Huffman's algorithm on C′C', which has n−1n - 1 symbols. By induction they build an optimal tree T′T' for C′C', and by Lemma 2, expanding zz into xx and yy gives an optimal tree for CC. ■\blacksquare

Lemma 1 is the greedy-choice property and Lemma 2 the optimal substructure. Notice how Lemma 2 uses Lemma 1 inside its proof: optimal substructure for a greedy algorithm is about the subproblem that remains after the greedy choice, so the competitor SS must first be brought into a form that makes the same choice.

Checking by brute force

To test the theorem independently of the proof, compute the optimum by brute force. A full binary tree with nn leaves corresponds to a multiset of leaf depths satisfying the Kraft equality ∑c2−d(c)=1\sum_{c} 2^{-d(c)} = 1, and every such multiset is realised by some full tree. Given the depths, the best assignment of symbols puts the most frequent symbols at the smallest depths (the swap of Lemma 1 again). So the optimum is a minimum over depth multisets, which is small enough to enumerate for n≤8n \le 8.

python · try it yourself
import heapq, random
from itertools import combinations_with_replacement

def huffman_cost(freqs):
    if len(freqs) == 1:
        return freqs[0]
    h = list(freqs); heapq.heapify(h); total = 0
    while len(h) > 1:
        a = heapq.heappop(h); b = heapq.heappop(h)
        total += a + b
        heapq.heappush(h, a + b)
    return total

def brute_force_cost(freqs):
    n = len(freqs)
    best = None
    for depths in combinations_with_replacement(range(1, n), n):     # sorted depth multisets
        if sum(1 << (n - 1 - d) for d in depths) == 1 << (n - 1):      # Kraft sum 1: a full binary tree
            cost = sum(f * d for f, d in zip(sorted(freqs, reverse=True), depths))
            best = cost if best is None else min(best, cost)
    return best

print("example:", huffman_cost([21, 9, 16, 4, 30, 8, 12]), brute_force_cost([21, 9, 16, 4, 30, 8, 12]))
rng = random.Random(12)
ok, tested = True, 0
for _ in range(100):
    freqs = [rng.randint(1, 50) for _ in range(rng.randint(2, 7))]
    ok &= huffman_cost(freqs) == brute_force_cost(freqs)
    tested += 1
print(f"Huffman equals the brute-force optimum on {tested} random alphabets:", ok)
example: 261 261
Huffman equals the brute-force optimum on 100 random alphabets: True

The exchange, numerically

The program builds a deliberately bad code for the example alphabet, then applies the swaps of Lemma 1 one at a time and prints the cost after each.

python · try it yourself
freq = {"A": 21, "B": 9, "C": 16, "D": 4, "E": 30, "F": 8, "G": 12}
# a valid full-tree depth assignment (Kraft sum 1), but with the symbols placed badly
depth = {"E": 4, "A": 4, "C": 4, "G": 4, "B": 2, "F": 2, "D": 2}
assert sum(2 ** -d for d in depth.values()) == 1

def cost(depth):
    return sum(freq[s] * depth[s] for s in freq)

print("bad placement:", cost(depth))
changed = True
while changed:                                    # swap any pair where the rarer symbol is shallower
    changed = False
    for a in freq:
        for b in freq:
            if freq[a] < freq[b] and depth[a] < depth[b]:
                gain = (freq[b] - freq[a]) * (depth[b] - depth[a])
                depth[a], depth[b] = depth[b], depth[a]
                print(f"swap {a} (freq {freq[a]}) and {b} (freq {freq[b]}): saves {gain:3}, cost now {cost(depth)}")
                changed = True
print("final depths:", dict(sorted(depth.items())))
bad placement: 358
swap B (freq 9) and A (freq 21): saves  24, cost now 334
swap D (freq 4) and B (freq 9): saves  10, cost now 324
swap F (freq 8) and C (freq 16): saves  16, cost now 308
swap A (freq 21) and E (freq 30): saves  18, cost now 290
swap B (freq 9) and A (freq 21): saves  24, cost now 266
final depths: {'A': 2, 'B': 4, 'C': 2, 'D': 4, 'E': 2, 'F': 4, 'G': 4}

Each swap saves exactly (a.freq−x.freq)(d(a)−d(x))(a.\mathit{freq} - x.\mathit{freq})(d(a) - d(x)) bits, the product in Lemma 1. When no swap helps, the depths are sorted against the frequencies, the best this tree shape allows. The result is 266, still worse than Huffman's 261: swaps only reassign symbols to leaves, while Huffman also chooses the shape (leaf depths 2,2,3,3,3,4,42, 2, 3, 3, 3, 4, 4 instead of this tree's 2,2,2,4,4,4,42, 2, 2, 4, 4, 4, 4).

A linear-time variant

If the frequencies come sorted, the priority queue can be replaced by two plain queues: one holding the original symbols in increasing order, one receiving the merged trees. Merged weights are produced in non-decreasing order (each merge takes the two smallest available weights, and they never decrease), so the second queue stays sorted automatically, and the two smallest items are always at the fronts of the two queues. Every step is O(1)O(1), so the algorithm is Θ(n)\Theta(n) after sorting.

In C++

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <deque>
#include <vector>

long long huffman_two_queues(std::vector<long long> freqs) {
    std::sort(freqs.begin(), freqs.end());
    if (freqs.size() == 1) return freqs[0];
    std::deque<long long> leaves(freqs.begin(), freqs.end()), merged;
    auto pop_min = [&]() {
        std::deque<long long>& q = merged.empty() || (!leaves.empty() && leaves.front() <= merged.front()) ? leaves : merged;
        long long x = q.front();
        q.pop_front();
        return x;
    };
    long long total = 0;
    for (size_t k = 1; k < freqs.size(); ++k) {
        long long x = pop_min(), y = pop_min();
        total += x + y;
        merged.push_back(x + y);            // non-decreasing, so this queue stays sorted
    }
    return total;
}

int main() {
    std::printf("%lld\n", huffman_two_queues({21, 9, 16, 4, 30, 8, 12}));
    std::printf("%lld\n", huffman_two_queues({1, 2, 4, 8, 16, 32}));
    std::vector<long long> many;
    for (int i = 1; i <= 100000; ++i) many.push_back(1 + (1LL * i * i) % 1000);
    std::printf("%lld\n", huffman_two_queues(many));
}
261
119
753801119

Test yourself

In Lemma 1, swapping a least frequent symbol xx with a deepest leaf aa changes the cost by −(a.freq−x.freq)(d(a)−d(x))-(a.\mathit{freq} - x.\mathit{freq})(d(a) - d(x)). Why is this never positive?

  1. Because xx is always at the root
  2. Because a.freq≥x.freqa.\mathit{freq} \ge x.\mathit{freq} and d(a)≥d(x)d(a) \ge d(x), so the product is non-negative
  3. Because the tree is balanced
  4. Because frequencies are integers

If merging xx and yy into zz gives the tree T′T' for the reduced alphabet, what is B(T)B(T) for the expanded tree?

  1. B(T′)B(T')
  2. B(T′)+x.freq+y.freqB(T') + x.\mathit{freq} + y.\mathit{freq}
  3. B(T′)+z.freq⋅d(z)B(T') + z.\mathit{freq} \cdot d(z)
  4. 2B(T′)2 B(T')

Which depth multisets can be the leaf depths of a full binary tree with four leaves?

  1. {1,2,3,3}\{1, 2, 3, 3\} and {2,2,2,2}\{2, 2, 2, 2\}
  2. {1,1,2,2}\{1, 1, 2, 2\}
  3. {1,2,2,3}\{1, 2, 2, 3\}
  4. {2,2,3,3}\{2, 2, 3, 3\}