ENع
←Huffman codes
Lesson 28 · Greedy and divide and conquer

Huffman coding

14 min10 steps5 questionsAdvanced
About this lesson

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".

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 28 · Interactive
01 / 10

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. Every 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 heap
  3. Join 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 = 14
  4. Again: 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 = 39
  5. Trees 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 = 69
  6. Common 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 = 124
  7. One 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 = 224
  8. Read 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")
  9. 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%)
  10. 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

Quiz Unlocks after the last step.