Sub topic 5
Huffman Coding and Dynamic Programming Foundations
Assume you know Big-O notation, recursion, binary trees, and binary heaps. This chapter connects Huffman coding, a greedy algorithm, with the ideas that motivate dynamic programming.
Huffman coding and optimal prefix codes
A prefix code represents each symbol with a binary string such as 0 or 101. A prefix code is one in which no codeword is the prefix of another codeword. Therefore, encoded data can be decoded without separators.
Huffman coding builds a prefix code whose weighted average code length is minimum. Frequent symbols should receive short codes, while rare symbols can receive longer codes.
For each symbol, record its frequency. Repeatedly remove the two nodes with the smallest frequencies from a min-heap, combine them into a new node, and insert the combined node again. The final node is the root of the Huffman tree. Assign 0 to left edges and 1 to right edges.
| Symbol | Frequency | Example code |
|---|---|---|
| A | 45 | 0 |
| B | 13 | 101 |
| C | 12 | 100 |
| D | 16 | 111 |
| E | 9 | 1101 |
| F | 5 | 1100 |
The cost of a tree is its weighted path length:
\[ \text{cost}=\sum_x f(x)\cdot d(x) \]
Here, f(x) is the frequency of symbol x, and d(x) is its depth in the tree. Huffman’s algorithm minimizes this cost.
import heapq
def huffman_cost(frequencies):
heap = list(frequencies)
heapq.heapify(heap)
cost = 0
while len(heap) > 1:
first = heapq.heappop(heap)
second = heapq.heappop(heap)
combined = first + second
cost += combined
heapq.heappush(heap, combined)
return cost
print(huffman_cost([45, 13, 12, 16, 9, 5])) # 224The algorithm performs one heap insertion and removal for each merge. With n symbols, its time complexity is O(n log n).
Dynamic programming: optimal substructure and overlapping subproblems
Dynamic programming (DP) solves a problem by combining solutions to smaller subproblems. It applies when two properties hold:
- Optimal substructure: an optimal solution contains optimal solutions to its subproblems.
- Overlapping subproblems: the same smaller problems are solved repeatedly by a direct recursive method.
A DP solution defines a state, writes a recurrence, sets base cases, and computes each state once. Memoization stores results during recursion. Tabulation fills a table, usually from smaller states to larger states.
Huffman coding does not normally use DP because its greedy choice removes the need to compare many combinations. Problems such as 0/1 knapsack and longest common subsequence require DP because a locally attractive choice can prevent a globally optimal solution.
Exercise
Why must a Huffman implementation repeatedly combine the two smallest frequencies?
Show answer
The exchange argument shows that an optimal prefix-code tree can place the two least frequent symbols as deepest siblings. Combining them into one equivalent item preserves the remaining optimization problem.