Skip to content

Huffman coding

planning ahead

Level 3 of 3

Also called Huffman code and Optimal prefix code.

how it works

The idea on the watch page's first example, abracadabra, then the whole method, step by step.

Abracadabra has 11 letters but only 5 different ones: a 5 times, b and r twice, c and d once. A code gives each letter a string of 0s and 1s. 2 bits make only 4 strings, 00, 01, 10 and 11, too few for 5 letters. So give every letter 3 bits, and the word takes 33. Give the common letters short codes, and it takes fewer. Line the letters up lightest first, two of one weight in letter order: c, d, b, r, a. Take the two lightest and join them into one tree, weighing both. Repeat until one tree is left. The table below makes each join. Read each code from the top of the tree down: 0 for a join's first branch, 1 for its second. a is 0, b 110, c 100, d 101, r 111. No code begins another, which books call a prefix code. So the bits read back with no gaps: 01101110 cuts into 0, 110, 111 and 0, abra. The word takes 23 bits, not 33. Each join weighs at least the one before, as question 3 shows, so a second queue keeps the joins in order. The two lightest are always at the two queues' fronts; the drawing reads the two as one row. Lining the letters up is a sort, the watch page's merge sort, the earlier letter first on a tie: 1 + 1, then 2, then 4, so 8 comparisons. Then 4 joins. This page counts the comparisons. The code below does the same with Python's own sort.

jointakesweighs
J1c 1 and d 12
J2b 2 and r 24
J3J1 2 and J2 46
J4a 5 and J3 611
The joins on abracadabra. At J2, J1 and b both weigh 2, and the letter is taken first. J4 holds all 11 letters.
lettertimescodebits
a505
b21106
c11003
d11013
r21116
all1123
Each letter's bits are its times its code's length. a, the commonest, has the shortest code. The joins add up to the same, 2 + 4 + 6 + 11, as question 4 shows.
Abracadabra: 7 moments of its 11 steps, the steps between them left for the watch page
  1. step 1 of 11

    abcdr

    Count each letter of abracadabra: a 5, b 2, c 1, d 1 and r 2.

    what it remembers to know where it is
    trees in the queue
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 2 of 11

    c 1d 1b 2r 2a 5abcdr

    Line the letters up lightest first, a tie in letter order: c 1, d 1, b 2, r 2 and a 5.

    what it remembers to know where it is
    trees in the queue
    5

    watch from here

  3. step 4 of 11

    b 2r 2J1 2a 5abcdrJ12

    Join c and d under a new place, J1, weighing 2, both together, c on the left for 0 and d on the right for 1. Each join weighs at least as much as the one before it, so J1 goes behind any joins already in the queue.

    what it remembers to know where it is
    trees in the queue
    4

    watch from here

  4. step 6 of 11

    J1 2J2 4a 5abcdrJ12J24

    Join b and r under a new place, J2, weighing 4, both together, b on the left for 0 and r on the right for 1. Each join weighs at least as much as the one before it, so J2 goes behind any joins already in the queue.

    what it remembers to know where it is
    trees in the queue
    3

    watch from here

  5. step 8 of 11

    a 5J3 6abcdrJ12J24J36

    Join J1 and J2 under a new place, J3, weighing 6, both together, J1 on the left for 0 and J2 on the right for 1. Each join weighs at least as much as the one before it, so J3 goes behind any joins already in the queue.

    what it remembers to know where it is
    trees in the queue
    2

    watch from here

  6. step 10 of 11

    J4 11abcdrJ12J24J36J411

    Join a and J3 under a new place, J4, weighing 11, both together, a on the left for 0 and J3 on the right for 1. Each join weighs at least as much as the one before it, so J4 goes behind any joins already in the queue.

    what it remembers to know where it is
    trees in the queue
    1

    watch from here

  7. step 11 of 11

    J4 11abcdrJ12J24J36J411

    Done: the codes are a 0, b 110, c 100, d 101 and r 111. The text takes 23 bits this way, against 33 if every letter had a code of the same length.

    what it remembers to know where it is
    trees in the queue
    1

    watch from here

the steps, in plain words
  1. count each letter, and line the letters up lightest firstPython lines 10, 11, 12, 13 and 14
  2. while more than one tree is left in the queuePython line 23
  3. take the two lightest, at the front of the queuePython lines 18, 19, 20, 21 and 24
  4. join them under a new place weighing both, back in the queue by its weight: 0 to the left, 1 to the rightPython lines 25, 26 and 27
  5. each letter's code is the way down to it from the top: 0 for each step left, 1 for each step rightPython lines 28, 29, 30, 31, 32, 33, 34, 35, 36 and 37
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

from collections import deque


def huffman_coding(text):
    """Give each letter of text a code of 0s and 1s, the fewest bits in all.

    text is a word with two or more different letters. Returns a dict from
    each letter to its code; no letter's code begins another's.
    """
    weight = {}
    for letter in text:  # count each letter
        weight[letter] = weight.get(letter, 0) + 1
    # line the letters up lightest first, two of one weight in letter order
    letters = deque(sorted(weight, key=lambda x: (weight[x], x)))
    joins = deque()  # each join is at least as heavy as the last, so this stays in order too
    branches = {}  # each join's two branches, the first taken on the left

    def take():  # the lighter front of the two queues, the letter on a tie
        if not joins or (letters and weight[letters[0]] <= weight[joins[0]]):
            return letters.popleft()
        return joins.popleft()

    while len(letters) + len(joins) > 1:  # more than one tree left
        a, b = take(), take()  # the two lightest
        join = len(branches) + 1  # a join's name is the order it was made in
        weight[join], branches[join] = weight[a] + weight[b], (a, b)
        joins.append(join)  # back in the queue by its weight
    codes = {}
    stack = [(take(), "")]  # from the top down: 0 to the left, 1 to the right
    while stack:
        tree, code = stack.pop()
        if tree in branches:
            first, second = branches[tree]
            stack += [(second, code + "1"), (first, code + "0")]
        else:
            codes[tree] = code
    return codes

how it scales

The plot counts the sort's comparisons lining up nn different letters weighing 1 to nn, in two orders. Weights falling in letter order cost the fewest any order costs, and weights in the dearest order the most. Measured from 10 to 1,000.

Each mark across or up is ten times the one before. Both lines climb a little over one mark up for each mark across. The dearest order makes 589 at 100 letters and 8,985 at 1,000, about 15 times. The plot's note reads it further out, from a million to ten million letters: about 12 times. The extra over ten times comes from the log in n log⁡2 nn \,\log_2\, n, which section 4 derives.

comparisons to line the letters up, ten times more at each mark up

a secondslope 1.1102104106108101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107a secondslope 1.1101102103104105106107108109101102103104105106107

nn, how many different letters the text has, ten times more at each mark to the right

  • weights in the dearest ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
  • weights falling in letter ordersolid where measured by running it; dashed where its formula carries it on to ten million
how long the dearest order takes, at a billion comparisons a second
nncomparisons to line the letters uptime
1,0008,985about 9 microseconds
100,0001,592,993about 1.6 milliseconds
10,000,000226,648,193about 227 milliseconds

The comparisons to line the letters up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Huffman coding's comparisons yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each size n it builds two words of n
different letters weighing 1 to n: weights falling in letter order, the
fewest comparisons any order costs, and weights in the dearest order, the
most. It prints the comparisons the sort makes lining up the letters, by
count below, the watch page's merge in place of Python's own sorted. The
counts are the same on any computer; only the time differs.
"""

from collections import deque


def huffman_coding(text):
    """Give each letter of text a code of 0s and 1s, the fewest bits in all.

    text is a word with two or more different letters. Returns a dict from
    each letter to its code; no letter's code begins another's.
    """
    weight = {}
    for letter in text:  # count each letter
        weight[letter] = weight.get(letter, 0) + 1
    # line the letters up lightest first, two of one weight in letter order
    letters = deque(sorted(weight, key=lambda x: (weight[x], x)))
    joins = deque()  # each join is at least as heavy as the last, so this stays in order too
    branches = {}  # each join's two branches, the first taken on the left

    def take():  # the lighter front of the two queues, the letter on a tie
        if not joins or (letters and weight[letters[0]] <= weight[joins[0]]):
            return letters.popleft()
        return joins.popleft()

    while len(letters) + len(joins) > 1:  # more than one tree left
        a, b = take(), take()  # the two lightest
        join = len(branches) + 1  # a join's name is the order it was made in
        weight[join], branches[join] = weight[a] + weight[b], (a, b)
        joins.append(join)  # back in the queue by its weight
    codes = {}
    stack = [(take(), "")]  # from the top down: 0 to the left, 1 to the right
    while stack:
        tree, code = stack.pop()
        if tree in branches:
            first, second = branches[tree]
            stack += [(second, code + "1"), (first, code + "0")]
        else:
            codes[tree] = code
    return codes


def count(text):
    """How many comparisons the watch page's sort makes lining up the
    letters: in letter order, runs of 1, 2, 4 and on merged in neighbouring
    pairs, the lighter first, and on a tie the earlier letter."""
    weight = {}
    for letter in text:
        weight[letter] = weight.get(letter, 0) + 1
    runs = [[(weight[x], x)] for x in sorted(weight)]
    compared = 0
    while len(runs) > 1:
        merged = []
        for k in range(0, len(runs) - 1, 2):
            left, right = runs[k], runs[k + 1]
            run = []
            i = j = 0
            while i < len(left) and j < len(right):
                compared += 1
                if right[j] < left[i]:
                    run.append(right[j])
                    j += 1
                else:
                    run.append(left[i])
                    i += 1
            merged.append(run + left[i:] + right[j:])
        if len(runs) % 2 == 1:
            merged.append(runs[-1])
        runs = merged
    return compared


def letters_of(n):
    """n different letters in letter order: a to z, or past 26 letters from
    the Chinese characters on, one plane, so their order is their numbers'."""
    return [chr(97 + k) if n <= 26 else chr(0x4E00 + k) for k in range(n)]


def cheapest(n):
    """n letters weighing n down to 1 in letter order: the fewest comparisons."""
    return "".join(x * (n - k) for k, x in enumerate(letters_of(n)))


def dearest(n):
    """n letters weighing 1 to n in the dearest order: in every merge, the
    two heaviest sit in different runs."""
    order = [0] * n

    def deal(at, ranks):
        if len(ranks) == 1:
            order[at] = ranks[0]
            return
        split = 1
        while split * 2 < len(ranks):  # the largest power of 2 below the run's length
            split *= 2
        left, right = [], []
        for i, rank in enumerate(reversed(ranks)):  # from the heaviest down
            if i % 2 == 0 and len(right) < len(ranks) - split:
                right.insert(0, rank)
            else:
                left.insert(0, rank)
        deal(at, left)
        deal(at + split, right)

    deal(0, list(range(1, n + 1)))
    return "".join(x * order[k] for k, x in enumerate(letters_of(n)))


if __name__ == "__main__":
    print(f"{'n':>6} {'falling':>9} {'dearest':>9}")
    for n in (10, 20, 50, 100, 200, 500, 1000):
        print(f"{n:>6} {count(cheapest(n)):>9} {count(dearest(n)):>9}")

best, worst and average

Here best and worst say how the weights 1 to nn are handed to the letters: each letter gets one, and the cases differ only in which letter gets which. Which runs the sort merges depends only on nn; where each merge stops, when one run is used up, depends on the weights. The joins never move: n−1n - 1 on every word. No average is worked out.

A case is one order of the weights. A bound says how fast that order's cost grows as letters are added.

The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. In the dearest order at 1,000 letters, n⌈log⁡2 n⌉n \lceil \log_2\, n \rceil is 10,000, less 16 waiting and 999 for the merges: 8,985. The 10,000 is most of it. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
bestweights falling in letter orderworstweights in the dearest order
comparisons to line the letters upb1+b2+b4+…b_1 + b_2 + b_4 + \dots, the right runsn⌈log⁡2 n⌉−w−(n−1)n \lceil \log_2\, n \rceil - w - (n - 1)
joinsn−1n - 1n−1n - 1
how the comparisons to line the letters up grow in each case
tight, Θ\ThetaΘ(n log⁡2 n)\Theta(n \,\log_2\, n)Θ(n log⁡2 n)\Theta(n \,\log_2\, n)
ceiling, OOO(n log⁡2 n)O(n \,\log_2\, n)O(n log⁡2 n)O(n \,\log_2\, n)
floor, Ω\OmegaΩ(n log⁡2 n)\Omega(n \,\log_2\, n)Ω(n log⁡2 n)\Omega(n \,\log_2\, n)

extra memory: The letters and their weights, a queue of joins, and each join's two branches.

Extra memory is the room it needs on top of the input itself, while it runs.

wordweights in letter ordercomparisonsjoins
aaaabbbccd4, 3, 2, 143
abbcccdddd1, 2, 3, 443
abbbccdddd1, 3, 2, 453
Three words of 4 letters weighing 1 to 4. The comparisons move with the order of the weights, from 4 to 5. The joins stay at 3.

where the formula comes from

Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 counts the joins, and question 4 shows why the codes spend the fewest bits.

Question 1: how many comparisons, FF, does the sort make on nn letters with weights falling in letter order, from 2 up?
  1. the move: how the sort goes

    the line:
    runs of 1,2,4,…merged in pairs\begin{gathered} \text{runs of } 1, 2, 4, \dots \\ \text{merged in pairs} \end{gathered}
    the row: 5, 4, 3, 2, 111111start221round 141round 25round 32a run, its length insideno partner, carried downthe first runall in one runa merge in round 2, its numbers45232345goes straight in, the other run used up
    5 numbers stand for 5 letters' weights, falling. Round 2's merge, 4, 5 with 2, 3, compares 2 with 4, then 3 with 4. Then the right run is used up, and 4 and 5 follow with no comparison.
    roundrun lengthmergescomparisons
    1122
    2212
    3411
    all45
    Five letters, weights falling. In rounds 1 and 2 the last run waits.

    why it is allowed: The watch page's sort is merge sort, from the bottom up. Each letter starts as a run of 1, in letter order. Each round merges neighbouring runs, comparing their front letters and taking the lighter. A last run with no partner waits. Every run is 1, 2, 4 and on long, except perhaps a round's last, which is shorter. A last run is a right run or waits, so a right run is never the longer. Which runs meet depends only on nn, never on the weights.

  2. the move: a merge's least

    the line:
    a merge compares at leastits right run’s length\begin{gathered} \text{a merge compares at least} \\ \text{its right run's length} \end{gathered}

    why it is allowed: A merge stops when one run is used up, and each letter of that run needed one comparison to leave it. By line 1, the right run is never the longer. So whichever run is used up holds at least the right run's length. For 4, 5 with 2, 3, at least 2 comparisons.

  3. the move: weights falling, the right run is used up first

    the line:
    F=b1+b2+b4+…F = b_1 + b_2 + b_4 + \dots
    run lengthright runscomparisons
    15 of 15
    22 of 24
    41 of 44
    81 of 22
    all15
    Ten letters, weights falling. At run length 2 the last run waits, and at 4 the last 2 letters wait. At 8 the right run holds only those 2.

    why it is allowed: With weights falling, each right run's letters weigh less than the left run's beside it. So the right run is used up first, one comparison each, the least line 2 allows. b1b_1 adds up the right runs in the round of runs of 1, b2b_2 of runs of 2, and so on. For 5, 2 + 2 + 1.

  4. the move: a ceiling

    the line:
    F≤n2⌈log⁡2 n⌉F \le \frac{n}{2} \lceil \log_2\, n \rceil
    numberlog× 2+ 11021428316452.32103.32
    Top, numbers, each double the last; bottom, their logs, each 1 more. 5 lies between 4 and 8, so its log, about 2.3, rounds up to 3. 10 lies between 8 and 16, so its log, about 3.3, rounds up to 4.

    why it is allowed: In a pair the right run is never the longer, so a round's right runs hold at most half the letters, n2\frac{n}{2}. Run lengths double until one run holds all nn, so there are ⌈log⁡2 n⌉\lceil \log_2\, n \rceil rounds. Multiply the two. For 5, half of 5 times 3 rounds is 7.5, and FF is 5.

  5. the move: a simpler ceiling

    the line:
    F≤n log⁡2 nF \le n \,\log_2\, n

    why it is allowed: Rounding up adds less than 1, and when nn is 2 or more, log⁡2 n\log_2\, n is at least 1. So ⌈log⁡2 n⌉\lceil \log_2\, n \rceil is at most twice log⁡2 n\log_2\, n, and n2\frac{n}{2} times twice log⁡2 n\log_2\, n is n log⁡2 nn \,\log_2\, n. For 5, FF is 5, at most 11.6.

  6. the move: read the bound

    the line:
    F∈O(n log⁡2 n)F \in O(n \,\log_2\, n)

    why it is allowed: By line 5, with the fixed multiple 1.

  7. the move: a floor

    the line:
    F≥n4⌊log⁡2 n⌋F \ge \frac{n}{4} \lfloor \log_2\, n \rfloor
    run lengthfull pairs holdtheir right runsa quarter of 5
    1421.25
    2421.25
    Five letters. In each round with a full pair, the full pairs hold 4 of the 5, at least half, and their right runs 2, at least a quarter. 2 such rounds, so at least 2.5.

    why it is allowed: Take a round whose runs are rr long, with 2r2r at most nn, so at least one full pair of runs fits, 2r2r letters. What is left over is fewer than 2r2r, so the full pairs hold at least half the letters, and their right runs at least a quarter, n4\frac{n}{4}. Such rounds have rr as 1, 2, 4 and on, while 2r2r is at most nn, so there are ⌊log⁡2 n⌋\lfloor \log_2\, n \rfloor of them. By line 3, FF adds up every round's right runs, so multiply the two. For 5, rounds of 1 and 2, so at least 2.5.

  8. the move: the rounded log against the exact one

    the line:
     log⁡2 n is below j+1,at most 2j\begin{gathered} \,\log_2\, n \text{ is below } j + 1, \\ \text{at most } 2j \end{gathered}

    why it is allowed: Call line 7's rounded-down log jj. Rounding down took off less than 1, so log⁡2 n\log_2\, n is below j+1j + 1. From 2 up jj is at least 1, so j+1j + 1 is at most 2j2j. For 5, jj is 2, and the log of 5, about 2.3, is below 3, and 3 is at most 4.

  9. the move: drop the rounding

    the line:
    F≥n log⁡2 n8F \ge \frac{n \,\log_2\, n}{8}

    why it is allowed: By line 8, jj is at least half of log⁡2 n\log_2\, n. Put that into line 7, and n4\frac{n}{4} times half of log⁡2 n\log_2\, n is n log⁡2 n8\frac{n \,\log_2\, n}{8}. For 5, FF is 5, at least 1.45.

  10. the move: read the bound

    the line:
    F∈Ω(n log⁡2 n)F \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple an eighth.

  11. the move: both together

    the line:
    F∈Θ(n log⁡2 n)F \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 6 and 10 bound FF by the same growth.

try it with a small nn: at n=5n = 5, line 3 gives F=5F = 5, which you can work out by hand

Question 2: how many comparisons, MM, does the sort make on nn letters with weights in the dearest order, from 2 up?
  1. the move: a merge's most

    the line:
    runs of p and q letterscompare at most p+q−1\begin{gathered} \text{runs of } p \text{ and } q \text{ letters} \\ \text{compare at most } p + q - 1 \end{gathered}

    why it is allowed: Each comparison sends one letter into the new run. When one run is used up, the other still holds at least one letter, which follows with no comparison.

  2. the move: the dearest order

    the line:
    every merge’s two heaviestsit in different runs\begin{gathered} \text{every merge's two heaviest} \\ \text{sit in different runs} \end{gathered}
    run of weightsleft run getsright run gets
    1, 2, 3, 4, 5, 61, 2, 3, 54, 6
    1, 2, 3, 51, 32, 5
    1, 313
    2, 525
    4, 646
    Dealing 6 weights. 6 goes right, 5 left, 4 right, and a right run of 2 is full, so 1 to 3 go left. Each left run comes before its right run, so the order is 1, 3, 2, 5, 4, 6.

    why it is allowed: By question 1's line 1, the left run of a merge is a full run, 1, 2, 4 or on long. The right run holds at least 1 letter and no more than the left. So a run of mm letters splits into the largest power of 2 below mm and the rest. Deal the weights out from the heaviest down, one to the right run and one to the left in turn, until the right run is full. The rest go left. Then deal each run the same way.

  3. the move: each merge, line 1's most

    the line:
    every merge compares p+q−1\text{every merge compares } p + q - 1

    why it is allowed: By line 2, the run without the heaviest ends with the second heaviest. Every other letter is lighter and goes in first. When the second heaviest goes in, that run is used up and only the heaviest is left.

  4. the move: each merge, one less than it holds

    the line:
    comparisons: letters merged,less one for each merge\begin{gathered} \text{comparisons: letters merged,} \\ \text{less one for each merge} \end{gathered}
    mergemergedcomparisons
    1 with 321
    2 with 521
    4 with 621
    1, 3 with 2, 543
    1, 2, 3, 5 with 4, 665
    all1611
    The dearest order of 6 weights: 1, 3, 2, 5, 4, 6. In round 2 the run 4, 6 waits. 16 merged, 5 merges, 11 comparisons.

    why it is allowed: By line 3, each merge compares one less than it holds. Add that up over every merge.

  5. the move: the letters merged

    the line:
    letters merged:n⌈log⁡2 n⌉−w\begin{gathered} \text{letters merged:} \\ n \lceil \log_2\, n \rceil - w \end{gathered}

    why it is allowed: Each of the ⌈log⁡2 n⌉\lceil \log_2\, n \rceil rounds, as in question 1's line 4, merges every letter except a run that waits. ww adds up the letters that wait. For 6, 18 less 2, which is 16.

  6. the move: the merges

    the line:
    merges: n−1\text{merges: } n - 1

    why it is allowed: Each merge makes one run fewer, from nn runs to 1. For 6, 5.

  7. the move: put them together

    the line:
    M=n⌈log⁡2 n⌉−w−(n−1)M = n \lceil \log_2\, n \rceil - w - (n - 1)

    why it is allowed: Lines 4, 5 and 6 together. By line 1, no order makes more. For 6, 16 less 5, which is 11.

  8. the move: a ceiling

    the line:
    M≤n⌈log⁡2 n⌉M \le n \lceil \log_2\, n \rceil

    why it is allowed: By line 7, dropping the ww and the n−1n - 1 it takes away, as neither is below 0. For 6, 11 is at most 18.

  9. the move: a simpler ceiling

    the line:
    M≤2n log⁡2 nM \le 2n \,\log_2\, n

    why it is allowed: As in question 1's line 5, ⌈log⁡2 n⌉\lceil \log_2\, n \rceil is at most twice log⁡2 n\log_2\, n. For 6, whose log is about 2.58, at most 31.0.

  10. the move: read the bound

    the line:
    M∈O(n log⁡2 n)M \in O(n \,\log_2\, n)

    why it is allowed: By line 9, with the fixed multiple 2.

  11. the move: a floor

    the line:
    M≥n4⌊log⁡2 n⌋M \ge \frac{n}{4} \lfloor \log_2\, n \rfloor

    why it is allowed: By question 1's lines 2 and 3, every merge compares at least its right run, whatever the weights, and FF adds up the right runs. So MM is at least FF, and question 1's line 7 gives FF this floor. For 6, 11 is at least 3.

  12. the move: drop the rounding

    the line:
    M≥n log⁡2 n8M \ge \frac{n \,\log_2\, n}{8}

    why it is allowed: As in question 1's lines 8 and 9. For 6, at least 1.94.

  13. the move: read the bound

    the line:
    M∈Ω(n log⁡2 n)M \in \Omega(n \,\log_2\, n)

    why it is allowed: By line 12, with the fixed multiple an eighth.

  14. the move: both together

    the line:
    M∈Θ(n log⁡2 n)M \in \Theta(n \,\log_2\, n)

    why it is allowed: Lines 10 and 13 bound MM by the same growth.

try it with a small nn: at n=6n = 6, line 7 gives M=11M = 11, which you can work out by hand

Question 3: how many joins, JJ, does the method make on nn different letters, from 2 up, and why does each weigh at least the one before?
  1. the move: one tree fewer each join

    the line:
    J=n−1J = n - 1
    aftertrees left
    the start5
    J14
    J23
    J32
    J41
    Abracadabra's 5 letters, joined in 4 steps.

    why it is allowed: Each letter starts as a tree of its own, nn trees. Each join takes two trees and gives back one, until one is left. Whatever the weights. For 5, 4.

  2. the move: each join at least the last

    the line:
    each join weighs atleast the one before\begin{gathered} \text{each join weighs at} \\ \text{least the one before} \end{gathered}

    why it is allowed: A join takes the two lightest, so every tree left, and the join itself, weighs at least the heavier of them. The next join takes two such trees, so it weighs at least twice the heavier. The last weighed the heavier plus the lighter, no more. Abracadabra's weigh 2, 4, 6 and 11.

  3. the move: a ceiling

    the line:
    J≤nJ \le n

    why it is allowed: By line 1, as n−1n - 1 is less than nn.

  4. the move: read the bound

    the line:
    J∈O(n)J \in O(n)

    why it is allowed: By line 3, with the fixed multiple 1.

  5. the move: a floor

    the line:
    J≥n2J \ge \frac{n}{2}

    why it is allowed: From 2 up, 1 is at most half of nn, so n−1n - 1 is at least half of nn. For 5, 4 is at least 2.5.

  6. the move: read the bound

    the line:
    J∈Ω(n)J \in \Omega(n)

    why it is allowed: By line 5, with the fixed multiple a half.

  7. the move: both together

    the line:
    J∈Θ(n)J \in \Theta(n)

    why it is allowed: Lines 4 and 6 bound JJ by the same growth.

  8. the move: the sort grows faster

    the line:
    comparisons over joins:at least log⁡2 n8\begin{gathered} \text{comparisons over joins:} \\ \text{at least } \frac{\log_2\, n}{8} \end{gathered}

    why it is allowed: By question 1's lines 2, 3 and 9, any weights make at least n log⁡2 n8\frac{n \,\log_2\, n}{8} comparisons, and by line 3 the joins are at most nn. So the comparisons are at least log⁡2 n8\frac{\log_2\, n}{8} times the joins, a number that grows without end. It is 1 or more from 256 on, as the log of 256 is 8. At 1,000 letters, 999 joins against 4,932 comparisons with weights falling and 8,985 in the dearest order.

try it with a small nn: at n=5n = 5, line 1 gives J=4J = 4, which you can work out by hand

Question 4: why do the codes spend the fewest bits of any code where no letter's code begins another's? Let BB be a code's bits, and TT its bits after line 2's swap.
  1. the move: what a code costs

    the line:
    bits: each letter’s timesits code’s length, added up\begin{gathered} \text{bits: each letter's times} \\ \text{its code's length, added up} \end{gathered}

    why it is allowed: A code where no letter's code begins another's is a tree, every letter at the bottom, its code the way down to it. So a code's length is its letter's depth. Tattoo has t 3 times, o twice and a once. The method's code, t 0, a 10 and o 11, spends 3 + 2 + 4, which is 9.

  2. the move: swap a lightest letter deepest

    the line:
    swap a lightest letter intoa deepest place\begin{gathered} \text{swap a lightest letter into} \\ \text{a deepest place} \end{gathered}
    J2aJ1to
    A worse code for tattoo as a tree, a 0 at depth 1, t 10 and o 11 at depth 2. 3 times 2, 1 times 1 and 2 times 2 is 11 bits.
    lettertimescode beforecode after
    t3100
    a1010
    o21111
    Swapping a and t turns the worse code into the method's code.

    why it is allowed: Take a code and a letter in one of its deepest places. Swap that letter with one of the lightest letters, whichever the method takes on a tie. The letter that is no lighter moves up, and the lighter one down, each by the same depth.

  3. the move: in the picture, count the change

    the line:
    T=B−2T = B - 2
    J2tJ1ao
    The method's code for tattoo, t 0 at depth 1, a 10 and o 11 at depth 2. 9 bits.

    why it is allowed: In the picture, t, appearing 3 times, moves up 1 and saves 3 bits. a, appearing once, moves down 1 and adds 1. So 2 fewer, in this swap. BB is 11 and TT is 9.

  4. the move: never dearer

    the line:
    T≤BT \le B

    why it is allowed: In any swap of line 2, the letter moving up appears at least as often as the one moving down, and both move the same depth. It saves its times that depth; the other adds its own times that depth, no more. So the bits fall or stay. In the picture, 3 saved and 1 added.

  5. the move: the two lightest at the bottom

    the line:
    some code of the fewest bitspairs the two lightest, deepest\begin{gathered} \text{some code of the fewest bits} \\ \text{pairs the two lightest, deepest} \end{gathered}

    why it is allowed: Start from a code of the fewest bits. Each of its joins has two branches, or skipping a lone one would save bits; t 0, a 10 and o 110 spends 11, and o 11 spends 9. So its deepest join holds two letters. Swap the lightest into one branch, as in line 2, then the next lightest into the other. Line 4's reason holds for both: every other letter appears at least as often as either.

  6. the move: join them, one letter fewer

    the line:
    fewest for the word:the smaller word’s fewestplus the pair’s weight\begin{gathered} \text{fewest for the word:} \\ \text{the smaller word's fewest} \\ \text{plus the pair's weight} \end{gathered}
    wordcodesbits
    t 3, ao 3t 0, ao 16
    t 3, a 1, o 2t 0, a 10, o 119
    Tattoo with a and o as one letter, ao, weighing 3. Read down: split, 6 + 3 = 9. Read up: join the pair back, 9 - 3 = 6; this needs a and o paired, which line 5 gives.

    why it is allowed: Treat the two lightest as one letter weighing both, as the method's first join does, a smaller word. Splitting that letter one level down turns a code for the smaller word into one for the whole, at the pair's weight more. Joining the pair back undoes it. By line 5 some code of the fewest bits pairs them, so the fewest for the whole is the smaller word's fewest plus the pair's weight.

  7. the move: the method's codes are the fewest

    the line:
    the method’s code:the fewest bits\begin{gathered} \text{the method's code:} \\ \text{the fewest bits} \end{gathered}
    jointakesweighs
    J1a 1 and o 23
    J2t 3 and J1 36
    Tattoo's joins. Keep J1 as one letter: 2 letters are left, t and J1, 1 bit each, 6 bits. Split it into a and o, and 3 more make 9.

    why it is allowed: With 2 letters, no code spends less than 1 bit a letter, and the method's 0 and 1 spend exactly that. Each join is line 6's step, one letter fewer. So repeating it from 2 letters up, the method's code spends the fewest bits.

  8. the move: the bits from the joins

    the line:
    bits: the joins’weights added up\begin{gathered} \text{bits: the joins'} \\ \text{weights added up} \end{gathered}

    why it is allowed: A letter's depth is the number of joins above it, and each join weighs every appearance below it once. So adding the joins' weights counts each letter's times once for each join above it, its times its depth, the bits of line 1. Tattoo, 3 + 6, which is 9. Abracadabra, 2 + 4 + 6 + 11, which is 23.

try it with a small BB: at B=11B = 11, line 3 gives T=9T = 9, which you can work out by hand

count it yourself

The watch page's second example, the word abstract: a and t twice, b, c, r and s once. Its weights in letter order make the most comparisons 6 letters can: 6 times 3, less 2 waiting, less 5 merges, which is 11. The sort makes all 11 at step 2. Then each step joins two trees. The last columns are running totals.

abstract, every step written down
stepwhat happenscomparisons to line the letters upjoins
1Count each letter of abstract: a 2, b 1, c 1, r 1, s 1 and t 2.00
2Line the letters up lightest first, a tie in letter order: b 1, c 1, r 1, s 1, a 2 and t 2.110
3The two lightest at the front are b, weighing 1, and c, weighing 1.110
4Join b and c under a new place, J1, weighing 2, both together, b on the left for 0 and c on the right for 1. Each join weighs at least as much as the one before it, so J1 goes behind any joins already in the queue.111
5The two lightest at the front are r, weighing 1, and s, weighing 1.111
6Join r and s under a new place, J2, weighing 2, both together, r on the left for 0 and s on the right for 1. Each join weighs at least as much as the one before it, so J2 goes behind any joins already in the queue.112
7The two lightest at the front are a, weighing 2, and t, weighing 2.112
8Join a and t under a new place, J3, weighing 4, both together, a on the left for 0 and t on the right for 1. Each join weighs at least as much as the one before it, so J3 goes behind any joins already in the queue.113
9The two lightest at the front are J1, weighing 2, and J2, weighing 2.113
10Join J1 and J2 under a new place, J4, weighing 4, both together, J1 on the left for 0 and J2 on the right for 1. Each join weighs at least as much as the one before it, so J4 goes behind any joins already in the queue.114
11The two lightest at the front are J3, weighing 4, and J4, weighing 4.114
12Join J3 and J4 under a new place, J5, weighing 8, both together, J3 on the left for 0 and J4 on the right for 1. Each join weighs at least as much as the one before it, so J5 goes behind any joins already in the queue.115
13Done: the codes are a 00, b 100, c 101, r 110, s 111 and t 01. The text takes 20 bits this way, against 24 if every letter had a code of the same length.115

In all, 11 comparisons to line the letters up. The formula from section 4, n⌈log⁡2 n⌉−w−(n−1)n \lceil \log_2\, n \rceil - w - (n - 1), gives M=11M = 11 at n=6n = 6: the same.

where you meet it

A student found the method in 1951 and published it in 1952. It is inside DEFLATE, which most ZIP files and every PNG picture use.

  • Huffman's 1952 paper

    Robert Fano offered his class at MIT a paper on the best such code in place of the final examination, as the books tell. David Huffman, a student, found in 1951 that the tree is easy to build from the bottom, and published the method in 1952.

    source: D. A. Huffman, Proceedings of the IRE 40(9), 1952, pages 1098 to 1101, A method for the construction of minimum-redundancy codes (opens in a new tab) and G. Stix, Scientific American, September 1991, for 1951, and the books' volume three, chapter 37

  • DEFLATE, in ZIP and PNG

    DEFLATE squeezes a file in two steps. First it writes repeats as short notes, then it gives those notes, and the letters between them, Huffman codes. Most ZIP files and every PNG picture use it.

    source: RFC 1951 by P. Deutsch, 1996, DEFLATE compressed data format specification version 1.3 (opens in a new tab) and section 10.1 of the W3C's third edition PNG specification (opens in a new tab) and sections 4.1.3 and 4.4.5 of PKWARE's APPNOTE.TXT (opens in a new tab)

  • The books' shift

    The books code a delivery shift of 60 stops, each one of six letters: D 24 times, P 10, A 9, S 8, N 7 and R 2. A fixed code of 3 bits each takes 180 bits. Huffman's takes 141, the fewest of any code where no letter's code begins another's.

    source: the books' volume three, chapter 37

what is used instead

When one letter is nearly certain, it still costs at least 1 bit each time. Arithmetic coding, and now asymmetric numeral systems, give no letter a string of its own, and come closer to the least possible, as the books note (volume three, chapter 37).

how it compares

A fixed code gives every letter the same length. Huffman's gives the common letters short codes.

waybits for abracadabra
a byte a letter88
3 bits a letter33
Huffman's code23
A byte is 8 bits, so 11 letters take 88. 3 bits name up to 8 letters, enough for 5: 33. Huffman's code, 23.