Huffman coding
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A fixed-length code spends the same number of bits on every letter. Huffman's greedy algorithm gives common letters short codes and rare letters long ones, and no prefix-free code does better. Watch it build a code tree for six letters with a Python priority queue: pop the two smallest counts, join them, push the sum back. Then prove the greedy choice is safe with an exchange argument. This lesson uses the heaps and priority queues from earlier in this course, and the proof style of "Greedy choices: the exchange argument and when greedy fails".
Three bits per letter
A file of 100 letters uses only a to f: a 45 times, b 13, c 12, d 16, e 9, f 5. A fixed-length code gives each letter 3 bits (2³ = 8 codes cover 6): 300 bits. Can common letters get shorter codes?
letter count fixed code a 45 000 b 13 001 c 12 010 d 16 011 e 9 100 f 5 101 total 100 letters × 3 bits = 300 bits
اقرأ الدرس خطوة بخطوة
Three bits per letter
A file of 100 letters uses only a to f: a 45 times, b 13, c 12, d 16, e 9, f 5. A fixed-length code gives each letter 3 bits (2³ = 8 codes cover 6): 300 bits. Can common letters get shorter codes?
letter count fixed code a 45 000 b 13 001 c 12 010 d 16 011 e 9 100 f 5 101 total 100 letters × 3 bits = 300 bitsEvery letter in a queue
Huffman builds a code tree from the bottom up, rarest letters first. Each letter starts as a one-node tree in a priority queue keyed by its count (lines 3 and 4). heapify makes a min-heap, so heappop always returns the smallest count.
huffman(freq) with freq = [(45, 'a'), (13, 'b'), (12, 'c'), (16, 'd'), (9, 'e'), (5, 'f')] a leaf is (count, letter); an inner node is (count, left, right) pop order: f:5 e:9 c:12 b:13 d:16 a:45 the figure shows the queue in pop order; heapq stores a heapJoin the two rarest
Pop the two smallest counts, f 5 and e 9 (lines 6, 7). Join them under a new node of count 14 and push it back (lines 8, 9). Every f and e now needs one more bit: the bit total grows by 14.
first merge heappop → f:5 (left, bit 0) heappop → e:9 (right, bit 1) w = 5 + 9 = 14, heappush queue now: c:12 b:13 14 d:16 a:45 bit total: 0 + 14 = 14Again: smallest two
Repeat. The smallest two are now c 12 and b 13: they join under 25, which goes back in the queue. The bit total grows by 25, to 39. Greedy never looks ahead: it only asks which two counts are smallest right now.
second merge heappop → c:12 (left, bit 0) heappop → b:13 (right, bit 1) w = 12 + 13 = 25, heappush queue now: 14 d:16 25 a:45 bit total: 14 + 25 = 39Trees merge like letters
Now the smallest are the new node 14 and d 16. A whole tree is popped just like a letter: 14 and d join under 30, so f and e sink one level deeper. Bit total: 39 + 30 = 69.
third merge heappop → 14 (left, bit 0) heappop → d:16 (right, bit 1) w = 14 + 16 = 30, heappush queue now: 25 30 a:45 bit total: 39 + 30 = 69Common letters wait
25 and 30 join under 55. Notice that a, with 45, has waited the whole time: the most common letter is merged last, so it will sit nearest the root with the shortest code. Bit total: 69 + 55 = 124.
fourth merge heappop → 25 (left, bit 0) heappop → 30 (right, bit 1) w = 25 + 30 = 55, heappush queue now: a:45 55 bit total: 69 + 55 = 124One tree left
Last pair: a 45 and 55 make the root, count 100, the whole file. One tree is left, so the loop stops and line 10 returns it. Six letters took 5 merges, each a few O(log n) heap steps: O(n log n) in all.
fifth merge heappop → a:45 (left, bit 0) heappop → 55 (right, bit 1) w = 45 + 55 = 100, heappush queue now: 100 bit total: 124 + 100 = 224Read the codes
From the root, left is 0 and right is 1. e is right, right, left, right: 1101. Likewise a = 0, c = 100, b = 101, d = 111, f = 1100. Letters sit only at leaves, so no code starts another.
letter count code bits a 45 0 1 b 13 101 3 c 12 100 3 d 16 111 3 e 9 1101 4 f 5 1100 4 decode 1101 0 101: e a b def codes(t, pre=""): if len(t) == 2: return {t[1]: pre} return codes(t[1], pre + "0") | codes(t[2], pre + "1")224 bits instead of 300
Cost = sum of count × length: 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4 = 224 bits, 25% fewer than 300. That equals 14 + 25 + 30 + 55 + 100: a merge adds a bit per letter below it.
a 45 × 1 = 45 b 13 × 3 = 39 c 12 × 3 = 36 d 16 × 3 = 48 e 9 × 4 = 36 f 5 × 4 = 20 total 224 bits merge counts: 14 + 25 + 30 + 55 + 100 = 224 fixed-length: 300 bits, saving 76 (25%)Why greedy is optimal
Exchange argument: some best tree has the two rarest letters as deepest siblings; swapping them down never raises the cost. Merging them into one letter of count 14 cuts every cost by 14, so a best smaller tree gives a best tree. Induction ends it.
greedy choice (CLRS Lemma 16.2): x, y rarest → some optimal tree has them as sibling leaves at maximum depth (swap, cost does not rise) optimal substructure (CLRS Lemma 16.3): replace x, y by z with f(z) = f(x) + f(y): B(T) = B(T′) + f(x) + f(y) here 224 = 210 + 5 + 9 induction on the number of letters finishes the proof
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Which set of codes is prefix-free?
In 0, 10, 11 no code is the start of another. In the other sets 0 starts 01, 1 starts 10, and 0 starts 00, so a bit string could split in more than one way.
02Counts are a 45, b 13, c 12, d 16, e 9, f 5. Which two trees does Huffman's algorithm join first?
It always pops the two smallest counts from the priority queue: f 5 and e 9. They join under a node of count 14.
03The merges in the lesson made nodes of count 14, 25, 30, 55 and 100. How many bits does the Huffman code use for the whole file?
Each merge pushes every letter below it one level deeper, adding one bit per occurrence. So the total is 14 + 25 + 30 + 55 + 100 = 224 bits, the same as 45·1 + 13·3 + 12·3 + 16·3 + 9·4 + 5·4.
04What does the exchange argument show?
Swapping the two rarest letters with the deepest pair of siblings never raises the cost, so some optimal tree joins them first. That is exactly the greedy choice Huffman makes.
05With a binary heap as the priority queue, how long does Huffman's algorithm take for n distinct letters?
There are n − 1 merges. Each does two pops and one push, and each heap operation costs O(log n), so the loop costs O(n log n). heapify at the start is only O(n).
المسرد
- Fixed-length code
- A code that gives every symbol the same number of bits, such as 3 bits for up to 8 symbols.
- Prefix-free code
- A code in which no codeword is the start of another, so a bit string splits into codewords in only one way. Often just called a prefix code.
- Code tree
- A binary tree for a prefix-free code: letters sit at the leaves, a left edge means 0 and a right edge means 1, and a letter's code is the path from the root.
- Priority queue
- A collection that always hands back its smallest item first. Python's heapq module keeps one as a binary min-heap.
- Greedy algorithm
- An algorithm that makes the choice that looks best right now and never undoes it.
- Exchange argument
- A proof that swaps parts of an optimal solution to show some optimal solution agrees with the greedy choice.
- Cost of a code
- The total number of bits it uses: the sum over letters of count × code length.
الملاحظات والمصادر
- The code card relies on all counts in the queue being different. With a tie, Python compares the second items of two tuples, and a letter against a tree raises TypeError. The heapq docs suggest a counter as a tie-breaker: (count, next(tick), tree). Ties also mean several optimal trees exist, all with the same cost.
- The queue is drawn in pop order to make it easy to read. heapq really stores a binary heap, which is only partly sorted, but heappop always returns the smallest item. heapify runs in linear time and each push or pop in O(log n), so n letters cost O(n log n).
- The 300 and 224 bit totals count only the coded letters. A real compressed file must also store the tree or the counts, so the decoder can rebuild it.
- The worked example is the one in CLRS §16.3 (§15.3 in the 4th edition), with counts per 100 letters instead of per 100,000. David Huffman published the method in 1952, as an MIT graduate student.
- Which child gets 0 is a convention. Here the first popped (smaller) tree goes left with bit 0. Swapping 0 and 1 anywhere gives different codes of the same lengths and the same cost.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 3rd ed. (MIT Press, 2009), §16.3 Huffman codes (§15.3 in the 4th ed., 2022)
- J. Huang, UT Arlington CSE 5311, Lecture 17: Greedy algorithms, Huffman coding (the CLRS example, Lemmas 16.2 and 16.3)
- M. Goemans, MIT 18.310 Principles of Discrete Applied Mathematics (Fall 2013), lecture notes: Huffman Codes
- Sedgewick and Wayne, Algorithms 4th ed., §5.5 Data Compression
- Python documentation: heapq, heap queue algorithm
اختبار يتاح بعد الخطوة الأخيرة.