Sub topic 7
Huffman Coding and Optimal Prefix Codes
This chapter assumes you know binary trees, binary heaps (priority queues), and the greedy exchange argument from the earlier chapters. It builds the optimal prefix code for a set of symbol frequencies.
The problem
A fixed-length code gives every symbol the same number of bits. A variable-length code gives frequent symbols short codewords and rare symbols long ones. Variable-length codes are only safe to decode when the code is a prefix code, meaning no codeword is a prefix of another. Then the bit stream can be decoded left to right with no separators.
Every prefix code corresponds to a binary tree. Symbols sit at the leaves, a left edge means 0, and a right edge means 1. The codeword length of a symbol equals its leaf depth. For frequencies f(c) and depths d(c), the cost to minimize is:
B(T) = sum over all symbols c of f(c) · d(c)
An optimal tree is always full: every internal node has two children. A node with one child could be removed, which would shorten some codewords.
The greedy algorithm
- Put every symbol in a min-heap keyed by frequency.
- Remove the two lowest-frequency nodes, x and y.
- Create a new internal node z with children x and y and frequency f(x) + f(y). Insert z into the heap.
- Repeat until one node remains. That node is the root.
With n symbols, the loop performs n − 1 merges, and each merge does O(log n) heap work. The total time is O(n log n). The tree has 2n − 1 nodes.
import heapq
from itertools import count
def huffman_codes(freq):
if not freq:
return {}
tie = count()
heap = [(f, next(tie), sym) for sym, f in freq.items()]
heapq.heapify(heap)
if len(heap) == 1:
return {heap[0][2]: '0'}
while len(heap) > 1:
f1, _, left = heapq.heappop(heap)
f2, _, right = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, next(tie), (left, right)))
codes = {}
def walk(node, prefix):
if isinstance(node, tuple):
walk(node[0], prefix + '0')
walk(node[1], prefix + '1')
else:
codes[node] = prefix
walk(heap[0][2], '')
return codes
freq = {'a': 45, 'b': 13, 'c': 12, 'd': 16, 'e': 9, 'f': 5}
codes = huffman_codes(freq)
print(sorted(codes.items()))
print(sum(freq[s] * len(codes[s]) for s in freq)) # 224The counter in each heap entry breaks frequency ties. Without it, Python would try to compare a symbol string with a tuple and could raise a TypeError.
Worked trace
Use frequencies a:45, b:13, c:12, d:16, e:9, f:5, which total 100.
| Step | Merge | New node |
|---|---|---|
| 1 | f(5) + e(9) | 14 |
| 2 | c(12) + b(13) | 25 |
| 3 | 14 + d(16) | 30 |
| 4 | 25 + 30 | 55 |
| 5 | a(45) + 55 | 100 |
The codes are a=0, c=100, b=101, f=1100, e=1101, d=111. The cost is 45·1 + (12+13+16)·3 + (5+9)·4 = 45 + 123 + 56 = 224 bits per 100 symbols. A fixed 3-bit code needs 300 bits, so the saving is about 25%.
Why the greedy choice is correct
The proof has two parts, and GATE questions often rely on both.
- Greedy-choice property (exchange argument). Let x and y be the two lowest-frequency symbols. Some optimal tree has x and y as sibling leaves at the maximum depth. Take any optimal tree and swap x and y with the deepest sibling pair a and b. Because f(x) ≤ f(a) and d(x) ≤ d(a), the swap changes the cost by −(f(a) − f(x))(d(a) − d(x)), which is never positive. So the swap never makes the tree worse.
- Optimal substructure. Replace x and y by one symbol z with f(z) = f(x) + f(y). For the resulting tree T′, B(T) = B(T′) + f(x) + f(y). The extra term does not depend on the shape of T′, so minimizing B(T′) minimizes B(T).
Together, these show that each merge can be fixed permanently and the rest solved as a smaller instance of the same problem.
Edge cases and gotchas
- Ties give different trees. Equal frequencies can be merged in different orders and produce different codewords. The total cost B(T) is the same for every valid choice. Exam questions that ask for cost are well defined, but questions that ask for a specific codeword may not be.
- One symbol. The merge loop never runs, so the code needs a rule. The usual choice is a 1-bit code.
- Maximum code length. The longest codeword can be n − 1 bits. This happens with skewed frequencies such as 1, 1, 2, 3, 5, 8, ... (Fibonacci numbers). The shortest codeword is at least 1 bit.
- Sorted input. If the frequencies are already sorted, a two-queue method builds the tree in O(n). One queue holds the original leaves and the other holds merged nodes. Merged nodes come out in nondecreasing order, so each queue's front is its minimum.
- Not the same as fixed-length coding. If all frequencies are equal and n is a power of 2, Huffman coding produces a complete tree, and every codeword has log₂ n bits.
Exam shortcuts
- Total encoded bits = sum of all internal-node weights, because each merge adds its weight once for every leaf below it. In the trace: 14 + 25 + 30 + 55 + 100 = 224.
- To count the bits needed for a message, multiply each symbol's count by its codeword length.
- For n symbols, the tree has n leaves and n − 1 internal nodes.
Exercise
Symbols with frequencies 5, 9, 12, 13, 16, 45 are Huffman coded. Using the internal-node-sum shortcut, what is the total cost? Also, how many internal nodes does the tree have?
Show answer
The merges produce internal nodes 14, 25, 30, 55 and 100. Their sum is 14 + 25 + 30 + 55 + 100 = 224 bits. With n = 6 symbols the tree has n − 1 = 5 internal nodes, which matches the five merges.
Exercise
Why does the heap-based algorithm run in O(n log n) time, and when can it run in O(n)?
Show answer
It does n − 1 merges, and each merge does two extract-min operations and one insert, each O(log n), giving O(n log n). If the symbols are already sorted by frequency, a two-queue method (one queue of leaves, one of merged nodes) replaces the heap with constant-time queue operations, giving O(n).