Unequal frequencies and codeword boundaries
A fixed-length code spends the same number of bits on every symbol. That is
simple, but it ignores a useful fact about real data: symbols usually occur at
very different frequencies. If a occupies almost half a file while f
appears only occasionally, making their codewords equally long wastes space.
Huffman coding uses a binary tree and a min-priority queue to assign short paths
to frequent symbols and longer paths to rare ones.
Variable-length words save space only if a decoder can recognize their boundaries. Placing symbols at leaves makes a completed word impossible to confuse with the beginning of a longer one. The tree then serves two roles: its paths determine the codewords, and their lengths together with the symbol frequencies determine the payload cost.
The same priority-queue operations also solve a different problem. When merging sorted lists, the next output is the smallest among the lists' current heads. A min-heap keeps precisely those candidates and avoids rescanning all heads after every output. Both applications repeatedly maintain a small frontier of currently eligible minimum items.
Frequencies, prefix codes, and payload cost
Definition 6.2.1
(Frequency model)
Let a nonempty alphabet contain distinct symbols. A symbol x has frequency
, which may be a positive count or a probability. Counts determine how
many copies occur; probabilities should sum to 1. Multiplying every weight by
the same positive constant does not change which pairs are smallest, so the
Huffman merge structure is unchanged.
Definition 6.2.2
(Binary prefix code)
A binary code assigns each symbol a finite bit string. It is prefix-free if
no symbol's complete codeword is a prefix of another symbol's codeword. In a
prefix-code tree, symbols label leaves, left edges are conventionally 0, and
right edges are conventionally 1; a codeword is the root-to-leaf path.
Definition 6.2.3
(Weighted code length)
For codeword length , the weighted length is . With probabilities, is the expected bits per symbol. With occurrence counts, it is the exact number of encoded payload bits. This calculation does not include storage for the code tree, a frequency header, file metadata, or byte padding; those costs must be added in a complete file-format analysis.
The repeated two-minimum construction
Create one leaf for each symbol and key it by frequency. Put all leaves in a min-heap. Repeatedly remove the two minimum-weight roots, attach them below a new internal node whose weight is their sum, and insert that node back into the heap. With leaves there are exactly merges, because every merge reduces the number of heap items by one.
HUFFMAN(symbols with positive weights)
H = a min-heap containing one leaf per symbol
while size(H) > 1
x = deleteMin(H)
y = deleteMin(H)
z = a new internal node with weight x.weight + y.weight
z.left = x
z.right = y
insert(H, z)
return deleteMin(H)
Choosing x as the left child gives a reproducible convention, but exchanging
the left and right children of any internal node remains valid. Such an
exchange changes bit strings, not codeword lengths or storage cost. Equal
weights can also permit different merge orders. Therefore a Huffman tree need
not have a unique printed code table.
At every stage the heap contains roots of disjoint subtrees whose leaves partition the alphabet. A merge preserves that forest invariant: it replaces two disjoint parts by their union and gives the new root the sum of all leaf weights below it. When one root remains, every symbol occurs exactly once as a leaf of one full binary tree.
If the input contains symbols, counting frequencies costs . A
bottom-up heap can be built from the leaves in time. The
rounds each perform two deleteMin operations and one insertion, each bounded
by , so tree construction is . Visiting the final
tree to record each leaf and its code length takes . Writing a separate
bit string for every codeword also costs time proportional to their total
length, : unlike the tree, the table repeats shared path
prefixes. Thus preprocessing with an explicit code table takes
; if a frequency table is already supplied, the scan
is absent. Encoding performs one code-table lookup per input symbol plus work
proportional to the number of bits emitted. With nonempty codewords, decoding
is linear in the number of bits read.
For an alphabet with just one symbol, the merge loop produces a one-node tree
and an empty path. An empty code cannot distinguish one occurrence from several.
A format must therefore assign a nonempty word such as 0, or separately store
the number of symbols. The root-to-leaf decoding theorem below assumes at least
two leaves, so every codeword consumes at least one bit.
With frequencies , the successive Huffman merges are , , , , and . The sum of merge weights is bits. With frequencies , one tie-breaking order merges , , and , giving bits.
What the code tree guarantees
Theorem 6.2.4
(Leaf codes are prefix-free)
If every source symbol labels a leaf of a binary tree and its code is the root-to-leaf edge sequence, then no source-symbol codeword is a prefix of another source-symbol codeword.
Theorem 6.2.5
(A prefix-code stream has unique symbol boundaries)
For a known prefix-code tree with at least two leaves, every bit string that is a concatenation of its leaf codewords has exactly one left-to-right decoding into source symbols, including the empty stream as the empty symbol sequence.
Theorem 6.2.6
(Merge-sum identity)
For a tree made by repeatedly joining two weighted roots, the weighted external path length equals the sum of the weights of all newly created internal nodes. Equivalently, summing over leaves gives the same number as summing the combined weight written at every merge.
Prefix-freeness guarantees decoding, while the merge-sum identity checks the cost of the constructed tree. Neither statement proves that the two-minimum Huffman construction minimizes cost among all binary prefix trees. That is a separate greedy-optimality theorem. After establishing the decoding and cost facts, we will prove that theorem by changing an optimal tree without making its cost worse.
Leaves determine boundaries; merges determine cost
For the first proposition, suppose one leaf code were a prefix of another. Following the shorter code from the root would reach its leaf and then would have to continue along more edges to reach the second symbol. A leaf has no children, so this is impossible. The claim depends on symbols being stored at leaves rather than at internal nodes.
For unique decoding, start at the root and consume bits one at a time. The first reached leaf forces the first symbol: stopping earlier would mean an internal node had a code, while continuing would mean a leaf code was a prefix of a longer code. Output that leaf, return to the root, and repeat. Induction on the remaining codewords gives a unique complete decoding. If the stream ends partway through a codeword, at an internal node other than the root, it is truncated or invalid rather than a second valid decoding.
For the merge-sum identity, joining roots of weights and increases the depth of every leaf in those two subtrees by one. The weighted-length increase is therefore exactly , the new internal-node weight. Starting from isolated leaves at depth zero and summing this increase across all merges gives the final weighted external path length. This is also a powerful arithmetic cross-check: a code-length calculation and a merge-total calculation should agree.
Concept lensCombinatorial
A prefix code described by its lengths alone
Give the root of a full binary tree a budget of and let each internal node pass half of its share to each child; a leaf at depth then holds , and the leaf shares add up to exactly . Conversely, any positive integer lengths with belong to some prefix code: assign codewords in order of increasing length. The coding problem is therefore to minimize over such length lists.
Why the two smallest weights may safely be merged
The greedy rule makes a permanent decision before it knows the finished tree: the first two chosen symbols will become siblings. To justify that decision, we do not need to show that every optimal tree already has those siblings. It is enough to show that some optimal tree has them, then reduce the remaining problem to the same kind of problem with one fewer symbol.
Theorem 6.2.7
(Huffman optimality for binary prefix codes)
For an alphabet of at least two symbols with positive weights, repeatedly merging two minimum-weight current items produces a binary prefix code of minimum weighted length . Ties may be resolved in any order. The comparison is among codes assigning one binary codeword to each symbol, with no extra restrictions on codeword lengths or symbol order.
First restrict attention to full binary trees, in which every internal node has two children. If a prefix-code tree has an internal node with only one child, remove that node and move its entire child subtree up one level. Every symbol is still a leaf and the code remains prefix-free, but every leaf in that subtree has a shorter path. Because the weights are positive, the cost strictly decreases. Thus an optimal tree has no one-child internal node. For a fixed number of symbols there are only finitely many full binary tree shapes and assignments of symbols to leaves, so a minimum is attained.
Now let a and b be two symbols of smallest weight. Choose a deepest leaf
in an optimal full tree, at depth . Its sibling must also be a leaf: if
the sibling were internal, it would have a leaf descendant deeper than .
Consequently there are two sibling positions at the maximum depth.
Proof X-ray
The exchange changes labels, not the tree shape
Suppose a lighter symbol of weight occupies depth , and a heavier symbol of weight occupies depth , with and . Exchange just their leaf labels. The change in weighted length is
All other leaves keep their contributions. The tree remains full and its leaf paths remain prefix-free. The inequality says precisely why placing a smaller weight deeper cannot hurt the objective; it is not a claim that the codeword bits themselves remain unchanged.
Put a at the first chosen deepest position by such a swap, if it is not
there already. Next put b at the other position. The first position now
contains a, so the second swap leaves it fixed. Every other symbol has
weight at least that of b, and no position is deeper than , so the second
swap also cannot increase cost. Starting from an optimal tree, we have
therefore obtained another optimal tree in which a and b are deepest
siblings. Equal weights simply make some swaps cost-neutral. The conclusion
is existence of a suitable optimal tree, not uniqueness of its labels or shape.
Contract the siblings, then solve a smaller instance
Replace sibling leaves a and b by their parent, now treated as one leaf
z with weight . If that parent has depth , their
contribution before contraction is
All other contributions are unchanged. Writing T for the original tree and
T' for the contracted tree gives the exact relation
The amount added back does not depend on the shape chosen for the smaller
tree. If the contracted tree were not optimal for the reduced alphabet,
replace it by a cheaper reduced tree and expand z back into a and b.
The same fixed amount would be added, producing a cheaper original
tree and contradicting optimality. Conversely, an optimal reduced tree
expanded in this way has the same cost as the suitable original optimum,
because their contracted costs are both minimum. Thus an optimal solution of
the reduced problem gives an optimal solution of the original problem.
With two symbols, both leaves of a full tree have depth one, so Huffman's single merge is optimal. For more symbols, the exchange argument makes the first merge compatible with an optimum, and the contraction argument leaves exactly the same problem with one fewer item. Induction proves that all subsequent two-minimum merges are safe as well. Internal nodes must therefore re-enter the candidate set: after contraction, a combined subtree is a genuine weighted item of the smaller problem, not a finished object to set aside.
Counterexample mode
Two small weights are not necessarily the two smallest
Take weights a:1, b:2, c:3, and d:4. Huffman first merges
1+2=3; the current weights are then 3,3,4. Its remaining merges are
3+3=6 and 4+6=10, so the merge-sum identity gives cost 3+6+10=19.
The resulting code lengths for a,b,c,d are 3,3,2,1, giving the independent
check .
Suppose instead that the first merge uses 1+3=4. Even if every later merge
uses the current two minima, the remaining weights 2,4,4 give merges
2+4=6 and 4+6=10. The cost is 4+6+10=20. The two tied weights 4
may be exchanged, but either choice still gives cost 20. This is a valid
prefix tree, and every merge is arithmetically correct; it loses because its
first pair lacks the greedy-choice justification. A correct cost calculation
alone is therefore no proof of optimality.
The theorem concerns the weighted length of a symbol-by-symbol binary prefix code for the supplied weights. It does not include the cost of describing the code tree or guarantee the smallest whole file. Nor does it compare against methods that encode blocks of symbols or exploit changing context. Those methods change the optimization problem rather than contradict this theorem.
A six-symbol code and its cost
Worked example 6.2.8
(Complete six-symbol Huffman construction)
Consider the percentage frequencies
| symbol | a | b | c | d | e | f |
|---|---|---|---|---|---|---|
| frequency | 45 | 13 | 12 | 16 | 9 | 5 |
The first audit is 45 + 13 + 12 + 16 + 9 + 5 = 100. Start from the ascending
heap view 5, 9, 12, 13, 16, 45. The five merges are
f:5 + e:9 -> 14;c:12 + b:13 -> 25;(f,e):14 + d:16 -> 30;(c,b):25 + ((f,e),d):30 -> 55;a:45 + 55 -> 100.
After every insertion, the next two minima are selected from the whole heap,
not merely from the original leaves. With the lighter child placed left and
left/right edges labeled 0/1, the full tree is
(100)
0 / \ 1
a:45 (55)
0 / \ 1
(25) (30)
0/ \1 0/ \1
c:12 b:13 (14) d:16
0/ \1
f:5 e:9
Reading root-to-leaf paths gives
| symbol | code | length | frequency |
|---|---|---|---|
a | 0 | 1 | 45 |
b | 101 | 3 | 13 |
c | 100 | 3 | 12 |
d | 111 | 3 | 16 |
e | 1101 | 4 | 9 |
f | 1100 | 4 | 5 |
The length pattern also satisfies the complete-tree check
. Swapping children would produce different
bit strings, but the lengths 1, 3, 3, 3, 4, 4 would remain unchanged.
Worked example 6.2.9
(Three independent checks of the 224,000-bit result)
For a 100,000-character file, the counts are 45,000, 13,000, 12,000,
16,000, 9,000, and 5,000. The weighted average length is
0.45(1) + 0.13(3) + 0.12(3) + 0.16(3) + 0.09(4) + 0.05(4)
= 0.45 + 0.39 + 0.36 + 0.48 + 0.36 + 0.20 = 2.24 bits per character.
Hence the payload uses 100,000(2.24) = 224,000 bits. Direct integer
accounting gives the same value:
45,000 + 39,000 + 36,000 + 48,000 + 36,000 + 20,000 = 224,000.
The merge-sum check also agrees:
14 + 25 + 30 + 55 + 100 = 224 bit-percent units, hence 224,000 bits for
100,000 characters. Agreement among all three methods catches a wrong
frequency, merge, or code length.
Using eight bits per character for the ASCII comparison, the same payload would
use 100,000(8) = 800,000 bits, so Huffman saves 576,000 bits, or 72% of
that payload cost. A shortest fixed-length binary code for six symbols needs
bits per character, so it uses 300,000 bits. Huffman saves
76,000 bits, which is of the fixed-length cost.
Worked example 6.2.10
(Unique decoding without separators)
Using the table above, decode 1000101. Start at the root. Bits 100 reach
leaf c, so output c and return to the root. The next bit 0 reaches a.
The remaining bits 101 reach b. The only decoding is therefore cab, with
the forced split 100 | 0 | 101. Splitting into equal-width groups would be
incorrect because this is a variable-length code.
One heap candidate from each sorted list
For heap-based multiway merging, maintain the invariant that the heap contains exactly the first unconsumed item of every nonempty list. Because each list is sorted, every unconsumed item in that list is at least its head. The smallest heap key is therefore the smallest item remaining anywhere. Removing it is safe; inserting the successor from the same list restores the invariant.
Worked example 6.2.11
(Heap trace for merging three sorted lists)
Let L1 = [1, 7, 10], L2 = [2, 3, 11], and L3 = [4, 5, 6]. Initialize a
min-heap with (1,L1), (2,L2), (4,L3). Remove 1 and insert 7; remove 2
and insert 3; remove 3 and insert 11; remove 4 and insert 5. Continuing
in the same way outputs 1, 2, 3, 4, 5, 6, 7, 10, 11.
MERGE_K_SORTED_LISTS(lists)
H = empty min-heap
for each nonempty list i
insert(H, (lists[i].head.value, i, lists[i].head))
output = empty list
while H is not empty
(value, i, node) = deleteMin(H)
successor = node.next
append value to output
if successor exists
insert(H, (successor.value, i, successor))
return output
For sorted lists containing elements in total, the heap contains at
most heads. Each output performs one deleteMin and at most one insertion,
both , so for the total time is after heap
initialization. The auxiliary heap space is . A direct scan of all heads
would take , while concatenating and sorting ignores the supplied order
and costs . When , copying the one list is simply .
Common Mistakes
- Combining the two largest weights, or continuing to use a stale sorted list of original frequencies. Each round must select the two current minima, including internal nodes inserted by earlier rounds.
- Reading codes from leaves upward. Codes are root-to-leaf paths; reversing a path changes the code.
- Placing a source symbol at an internal node. Then its code can prefix a descendant's code, destroying separator-free decoding.
- Claiming that frequent symbols must always have strictly shorter codes. The construction tends to make them shallow, but equal lengths and tie-dependent trees are normal. The exact tree, not frequency rank alone, determines a codeword.
- Comparing only the number of codewords. Storage is the weighted sum of
lengths, and the stated
224,000bits excludes tree/header overhead. - Saying six symbols need two fixed bits because is close to six. Two bits represent only four distinct values; six symbols require three bits.
- Putting every element from all lists in the merge heap. Only the current head of each nonempty list is eligible, so the heap should have at most items.
Summary
Huffman construction repeatedly joins the two minimum-weight roots in a
min-heap. With at least two symbols, the resulting leaf codes are nonempty
and prefix-free, so concatenated codewords decode uniquely. The exchange
argument places two minimum weights at deepest sibling leaves of some optimum;
contraction then reduces the problem while adding only their fixed weight sum.
Together these facts prove minimum weighted length in the stated prefix-code
model. For the normalized
six-symbol table, the merges are 5+9=14, 12+13=25, 14+16=30,
25+30=55, and 45+55=100; the lengths are 1,3,3,3,4,4, and a
100,000-character payload occupies exactly 224,000 bits. That saves
576,000 bits against the stated 8-bit ASCII comparison and 76,000 bits
against the shortest three-bit fixed-length code.
The heap is not specific to compression. For sorted lists, keeping one current head per nonempty list lets each of outputs choose the global minimum in time, for time after initialization and auxiliary space.
Exercises
- Starting from weights
5, 9, 12, 13, 16, 45, show every Huffman merge and the heap's remaining weights after each insertion. - Using the code table in the complete construction, decode
11011100111. Show the leaf boundaries rather than guessing equal-length groups. - Recompute the six-symbol payload cost by both weighted code lengths and the merge-sum identity. Then state the savings against 8-bit ASCII and a shortest fixed-length code for six symbols.
- Decide whether the set
{0, 01, 11}is prefix-free. Explain the practical decoding consequence. - Give heap pseudocode for merging sorted linked lists. State the heap invariant, time complexity in terms of total length , and auxiliary space complexity.
- Two symbols have weights
2and7and currently occupy depths1and3, respectively. Compute the change in weighted length when their leaf labels are exchanged. Explain why this swap preserves prefix-freeness. - A reduced Huffman instance contains a combined symbol
zof weight9representing original weights4and5. An optimal tree for the reduced instance has weighted length31. Find the weighted length after expandingz, and explain why its depth is unnecessary for this calculation.
Solutions
Solution · 1. Merge trace
The states are: merge 5+9=14, leaving 12,13,14,16,45; merge 12+13=25,
leaving 14,16,25,45; merge 14+16=30, leaving 25,30,45; merge
25+30=55, leaving 45,55; merge 45+55=100, leaving only the root. There
are five merges because six leaves require five reductions to one root.
Solution · 2. Decoding
The forced split is 1101 | 1100 | 111. These codewords reach e, f, and
d, respectively, so the decoded sequence is efd.
Solution · 3. Storage audit
The weighted sum is 45(1)+13(3)+12(3)+16(3)+9(4)+5(4)=224 bits per 100
characters. The merge sum is also 14+25+30+55+100=224. Scaling by 1,000
gives 224,000 bits. ASCII uses 800,000, so the saving is 576,000 bits.
Three-bit fixed coding uses 300,000, so the saving is 76,000 bits.
Solution · 4. Prefix test
The set is not prefix-free because 0 is a prefix of 01. On seeing an
initial 0, a decoder cannot know from that bit alone whether to output the
first symbol or wait for the second bit. Leaf codes avoid this ambiguity.
Solution · 5. Multiway merge
Insert each nonempty list's first node into a min-heap keyed by value and tagged with its source list. Repeatedly remove the minimum, append it to the output, and insert its successor if one exists. The heap always holds exactly one next candidate per nonempty list. Its size is at most , so removals and at most insertions cost for . Finding the nonempty lists first requires inspecting all list headers, so the total time is , including initialization. The heap uses extra space.
Solution · 6. Exchange calculation
Before the swap the contribution is ; after the swap it is . The change is . The leaf positions and their bit paths do not change, so exchanging their symbol labels preserves prefix-freeness. Only the weights assigned to those path lengths change.
Solution · 7. Expansion has a fixed cost
Expanding z into its two children increases weighted length by ,
so the result is . At any depth , the contribution changes from
to ; the depth-dependent terms cancel. By the
exchange and contraction argument, expanding an optimum for this reduced
instance gives an optimum for the original instance when 4 and 5 are two
minimum weights at the corresponding greedy step.