第 17 章
Huffman 编码:交换论证与最优前缀码
前缀码让逐符号解码成为可能。用三次交换论证推出最优树的结构(最小与次小概率符号是兄弟),把问题收缩成规模更小的子问题,得到贪心算法;再用 Kraft 不等式证明最优码长夹在熵与熵加一之间。
Huffman Coding: Exchange Arguments and Optimal Prefix Codes
Prefix codes make symbol-by-symbol decoding possible. Three exchange arguments pin down the shape of an optimal tree — the two least likely symbols are siblings — which contracts the problem into a smaller one and yields a greedy algorithm. The Kraft inequality then proves the optimal length lies between entropy and entropy plus one.
篇内目录
- From a giant table to a tree
- Timeline
- Prefix codes
- Tree representation
- Why decoding is unique
- The problem: minimize expected length
- Three structural lemmas
- Lemma 1: the least likely symbol is deepest
- Lemma 2: the second least likely symbol is also deepest
- Corollary: they can be made siblings
- Contraction and recursion
- Building the subproblem
- Key lemma: is still optimal
- Huffman's algorithm
- Running example
- The Kraft inequality
- Performance:
- Lower bound
- Upper bound
- Amortizing the
- What this lecture establishes
- Comprehension check
- Relation to neighbouring lectures
从一张巨型码表到一棵树
上一讲的 Shannon 编码把整条长度 的消息映成一个二进制串。理论上最优,工程上不可行:消息共有 条,码表随 指数增长,编码要查表,解码要反查。
Huffman 的做法是把问题降一个维度:只对单个符号编码,得到前缀码,再把符号的码字首尾相接。解码时从左往右走一棵二叉树,读到叶子就切出一个符号。存储和运行时间只与字母表大小 有关。
这门课的历史注脚:1951 年,MIT 研究生 David Huffman 为了免修期末考试,在 Fano 教授给的学期论文题目里做出了这个算法。它今天仍是编码理论的基础内容。
本讲要回答两个问题:
- 怎样找到最优的前缀码?(贪心算法)
- 最优前缀码到底有多好?()
时间轴
| 时间 | 内容 |
|---|---|
| 0:00 | 回顾 Shannon 编码:渐近最优但码表指数大 |
| 4:01 | 前缀码的定义;码字之间不能互为前缀 |
| 5:28 | 前缀码 ↔ 二叉树:叶子是符号,左 0 右 1 |
| 8:59 | 逐符号解码;为什么切分唯一 |
| 12:44 | 问题:最小化每符号期望码长 |
| 15:43 | 假定已有最优树,反推它的结构性质 |
| 17:08 | 引理 1:最小概率符号在最深层 |
| 24:22 | 引理 2:次小概率符号也在最深层 |
| 32:16 | 推论:两者可以互为兄弟 |
| 34:36 | 合并两个符号,递归求解 |
| 37:15 | 关键引理:收缩后的树仍是子问题的最优解 |
| 51:07 | 用运行例子走一遍算法 |
| 1:01:07 | Kraft 不等式 |
| 1:06:07 | 定理: |
| 1:13:03 | 编码成对符号,把 摊薄成 |
前缀码
前缀码是函数 ,对任意两个不同符号 ,要求 不是 的前缀(两个方向都不允许)。
这比「码字互不相同」更强。例如 不是前缀码,因为 是 的前缀。
树表示
把码字排成二叉树:从根出发,走左孩子记 0,走右孩子记 1,每个符号对应从根到某个节点的路径。
前缀条件等价于:每个符号对应的是叶子,没有符号节点的下方还挂着别的符号。若某个符号在中途,它的码字就会成为后代符号码字的前缀。
反过来,任何一棵所有叶子都标了符号的二叉树(可以有空缺分支,但每个内部节点最多两个孩子)都给出一个前缀码。
解码为什么唯一
收到比特流后,从根开始逐位下行:走左或右,一旦碰到叶子就输出该符号,然后回到根继续。
唯一性由前缀条件保证:假设在某个位置有两种切分方式,一种把当前段读成符号 ,另一种读得更早或更晚。若另一种在更早处停下,那么另一个符号的码字是 的真前缀;若更晚,则 是它的真前缀。两种情况都违反前缀条件。
这就是「即时解码」:不需要看到整条消息,也不需要分隔符,读到叶子就能输出。
问题:最小化期望码长
设符号 出现概率为 、码长为 。目标是
这里 是每个符号的平均码长。若把长度 的块整体看成新字母表上的一个符号(共 个符号),同一个算法就能处理块编码,期望码长随之乘以 。所以先解决单符号问题就够了。
下文的讨论都假定概率两两不同、且合并产生的新符号也不与任何符号并列最小。有并列时算法照常工作,只是论证里要处理「至少并列」的说法。
三条结构引理
思路不是直接构造最优树,而是:假设已经拿到一棵最优树 ,反推它必须长什么样。反推出来的约束会强到足以确定整棵树。
所有证明共用同一个动作:交换两个符号的位置。交换不改变码字的集合,只改变哪个符号用哪个码字,因此前缀性质不受影响;只有期望长度会变。
引理 1:最小概率符号在最深层
引理。 设 是概率最小的符号,则 的码长至少并列最长。
证明。 反设不然。设 是最深的符号之一,且 。交换 与 的码字,其他符号不变。期望长度的变化只有两项:
由反设 ,且 ( 最小、无并列),故 。
也就是说交换后期望长度严格变小,与 的最优性矛盾。因此 必须处在最深层。
引理 2:次小概率符号也在最深层
引理。 设 是概率第二小的符号,则 也并列最长。
证明分两步。
第一步: 的父节点 必须有另一个孩子。若 只有 一个孩子,就把 直接挂到 的父节点上——由于 不对应任何符号(前缀条件),删掉 不会丢失信息,而 的码长减少 1,期望长度严格下降,矛盾。
设 的另一个孩子对应的符号是 ,于是 。
第二步:反设 。把 与 的码字交换。由引理 1 的同一计算,
这里 ,且 ( 是第二小, 不是最小),所以 ,同样与最优性矛盾。
因此 ,两者都在最深层。
推论:两者可以互为兄弟
由前两条引理, 与 都在最深层。 的父节点 有另一个孩子 ,且 。把 与 的位置互换:两者深度相同,期望长度不变,但互换后 与 共享父节点 。
所以不失一般性,最优树中最小与次小概率的两个符号是兄弟。这一步是后面收缩操作的合法性来源。
收缩与递归
构造子问题
把 、 从字母表中删去,加入一个新符号 ,令
其余符号的概率不变。这仍然是一个合法的概率分布。
在树上做同样的操作:删掉 、 两个叶子,把它们的父节点改成标有 的叶子。得到的树记作 ,它是新字母表 上的前缀码。
关键引理: 仍是最优的
引理。 若 是原问题的最优树,则 是新字母表 上的最优树。
证明。 反设存在更优的树 ,期望长度 。
把 中 所在的叶子展开成一个小二叉树:父节点下挂 、 两个叶子。这样得到原字母表 上的一棵合法前缀码。
它的期望长度是多少? 对每个非 符号的贡献与之前相同;对 的那部分,现在拆成 、 两个符号,且它们比 深一层,所以每遇到一次要多付 1 位。按概率加权,多付的是 。因此展开后的期望长度是
而 是由 做同样的展开得到的,所以
由 得 ,即我们造出了一棵比 更好的树,矛盾。
这个引理是整个算法的支点:原问题的最优解可以由子问题的最优解还原。于是可以反复收缩,直到只剩两个符号;两个符号的树只有一种形状(根下两个叶子),再逐层展开回去。
Huffman 算法
图:合并得到的树、码表与平均码长 2.32。
算法。 维护一个符号集合,每个符号带概率,并记录合并历史:
- 取出概率最小的两个符号(或合并出的新符号);
- 把它们合并成新符号,概率相加,记录「新符号的左孩子、右孩子」;
- 放回集合,重复,直到只剩一个符号;
- 从最后的根出发,按合并记录反向展开,左分支标 0、右分支标 1。
运行例子
符号与概率:。
| 步骤 | 合并 | 新概率 | 剩余符号与概率 |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | 完成 |
反向展开,得到码字:
| 符号 | 概率 | 码字 | 长度 |
|---|---|---|---|
| 0.40 | 0 | 1 | |
| 0.10 | 100 | 3 | |
| 0.05 | 1010 | 4 | |
| 0.07 | 1011 | 4 | |
| 0.18 | 110 | 3 | |
| 0.20 | 111 | 3 |
检查前缀条件:0 与所有以 1 开头的码字分开;100、1010、1011、110、111 互不为前缀(101 不是码字,但 1010 与 1011 在它下面分叉,合法)。
期望码长:
而这个信源的熵为
,落在定理承诺的区间里。
解码示例:比特流 1010 0 110 从根出发,读 1→0→1→0 到叶子,得 ;回到根读 0 得 ;再读 110 得 。结果是 。中途在 101 处不会停,因为 101 不是叶子。
Kraft 不等式
定理(Kraft)。 给定正整数 ,存在一棵叶子深度恰为这些值的二叉树,当且仅当
必要性。 深度为 的节点占用 的「概率质量」:根的质量是 1,每往下一层平分给两个孩子。叶子占用的质量互不重叠,总和不超过 1。
充分性。 把深度从小到大排序,依次在树上找最浅的可用位置放叶子;每放一个深度 的叶子,就把它下方 的质量占满。不等式保证轮到每个叶子时仍有空间。补充:课程把完整构造留到习题课,这里只给出要点。
性能:
下界
对任意前缀码,由 Kraft 不等式记 。令 ,则 是一个概率分布。由 Gibbs 不等式(相对熵非负),
最后一步用了
于是 。因为 ,有 ,故 :任何前缀码都不可能低于熵。这与上一讲 Shannon 的下界一致。
上界
构造一组候选码长
先验证 Kraft:因为 ,所以 ,于是
因此这样的树存在。它的期望长度满足
Huffman 码是所有前缀码中最优的,所以它的码长 。合起来
把 摊薄
逐符号编码时,每次都要多付至多 1 位。若把两个符号捆成一个新符号,字母表变成 个符号,问题仍然是一阶信源。新熵是多少?
于是对成对编码用 Huffman,期望码长满足 ,每符号是 。推广到长度 的块:,每符号偏差不超过 。
这就是对 Shannon 上界的改进:Shannon 给出的误差是 (可能是 或 ),Huffman 分块把它压到常数 1。
本节结论
- 前缀码 = 码字互不为前缀;等价于符号都在二叉树的叶子上。
- 逐符号编码让编解码从「查指数大的码表」变成「走一棵树」,且解码即时、唯一。
- 最优树的三个结构性质都由交换论证得到:最小概率在最深层、次小概率也在最深层、两者可互为兄弟。
- 把这对兄弟收缩成概率之和的新符号,子问题的最优解能还原原问题的最优解,于是贪心合并成立。
- Kraft 不等式刻画了「哪些码长组合可以实现」。
- Huffman 码满足 ;分块编码可把 摊成 。
理解检验
1. 为什么前缀码的解码不会有歧义?请用「假设存在另一种切分」的方式说明。
参考答案:设比特流有两种切分方式,在某个位置产生分歧:一种把从当前位置起的一段读成符号 ,另一种读成更短或更长的码字 。
- 若 更短,则 是 的前缀,违反前缀条件;
- 若 更长,则 是 的前缀,同样违反。
因此每个位置只有一种合法读法。这与「码字互不相同」不同:仅互不相同只能保证整条消息不撞车,不能保证从左到右即时切分。
2. 用交换论证证明:概率最小的符号必须位于最深层。
参考答案:设 概率最小,反设它的码长 不是最长。取一个最深的符号 ,则 。交换两者的码字后,前缀性质不变(变的只是哪个符号占用哪个码字),期望长度变化为
因为 且 ,所以 ,与最优性矛盾。故 必须在最深层。
3. 为什么 的父节点必须有另一个孩子?这一条在证明中起什么作用?
参考答案:若父节点 只有 一个孩子,那么 不对应任何符号(否则违反前缀条件)。把 直接挂到 的父节点上,删掉 ,树仍是合法前缀码,而 的码长减少 1,期望长度严格下降——矛盾。
这条结论的作用是: 的另一个孩子 与 深度相同,于是得到一个「与 同深度」的符号,可以拿来和次小概率符号 做交换,从而证明 也在最深层;进一步把 换到 的位置,就让 与 成为兄弟。
4. 设最优树 收缩后得到 ,证明 是子问题的最优解,并说明为什么 。
参考答案:反设子问题存在更优树 ,期望长度 。把 中 所在的叶子展开成父节点下挂 、 的结构,得到原问题的一棵合法前缀码。
在这个展开中,除 外的符号贡献不变;遇到 的地方原本在那里结束,现在要多走一层才到 或 ,所以期望长度增加 。故展开后的长度为 。
同理, 由 展开而来,长度 。于是 ,即存在比 更优的树,与 最优矛盾。
关系式 的直观含义:合并让子问题少算了一层的贡献,展开时再把这层补回来。
5. 对例子 执行一遍 Huffman 算法,验证 ,并说明它与熵的关系。
参考答案:合并顺序为 ,再 ,再 ,再 ,最后 。
反向展开得码字 、、、、、,长度分别为 。于是
熵为 。所以 成立。 比 高约 ,远小于 1——这个例子恰好落在区间靠下的位置,因为概率分布比较接近 2 的负幂。
6. 用 Kraft 不等式证明「取 一定可行」,并据此推出 。
参考答案:因为 ,所以 ,从而
Kraft 不等式保证存在对应的二叉树。它的期望长度为
Huffman 码在所有前缀码中最优,所以它的长度不超过这棵树,即 。
7. 为什么把符号两两打包能把 的损失减半?推广到 个符号是什么结论?
参考答案:打包后字母表有 个符号,概率为 。其熵为
最后一步分别对 与 求和并用 。对这个问题用 Huffman,得到 ,除以 2 得每符号 。
长度 的块同理:熵为 ,码长满足 ,每符号误差不超过 ,随 趋于 0。这正是把 Shannon 的 改进为常数 1 的方式。
8. Huffman 码已经是最优前缀码,为什么还可能需要 Shannon 的结论?
参考答案:两者回答不同的问题。Huffman 给出单符号、可实现的最优前缀码,但它的最优性只在「逐符号前缀码」这一类里成立;若允许对整块消息做任意单射编码(不要求前缀结构),理论上还能再省一点,Shannon 定理刻画的正是这个更大类的最优值 。
此外,Huffman 的 界需要知道概率分布、并在分布变化时重建树;Shannon 的结论不依赖具体算法,用来判断「还值不值得改进」。两者互补:Huffman 给构造,Shannon 给极限。
与前后课的关系
上一讲证明熵是任意块编码的渐近极限,但构造不可实现;本讲给出可实现且最优的前缀码,并把损失从 收紧到常数 1。
下一讲转向噪声信道:发送的比特可能被翻转,编码的目标从「更短」变成「更可靠」。Shannon 第二定理会用随机编码与典型性说明,只要码率低于信道容量,错误概率就能压到任意小。再往后两讲会用 Hamming 码与 Reed–Solomon 码给出具体的纠错构造。
From a giant table to a tree
Shannon's construction from the previous lecture maps a whole length- message to one binary string. It is asymptotically optimal but impractical: there are messages, so the codebook grows exponentially, and both encoding and decoding require searching it.
Huffman drops a dimension: encode one symbol at a time, using a prefix code, and concatenate the codewords. Decoding walks a binary tree from the root and emits a symbol whenever it hits a leaf. Storage and running time depend only on the alphabet size .
A historical footnote from the lecture: in 1951, MIT graduate student David Huffman developed this algorithm for a term paper, partly to avoid a final exam that Bob Fano had offered him. It is still a cornerstone of coding theory.
Two questions organize the lecture:
- How do we find the optimal prefix code? (A greedy algorithm.)
- How good is it? (.)
Timeline
| Time | Topic |
|---|---|
| 0:00 | Recap of Shannon coding: asymptotically optimal but exponentially large codebook |
| 4:01 | Definition of a prefix code: no codeword is a prefix of another |
| 5:28 | Prefix codes as binary trees: leaves are symbols, left 0, right 1 |
| 8:59 | Symbol-by-symbol decoding and why the split is unique |
| 12:44 | The problem: minimize the per-symbol expected length |
| 15:43 | Assume an optimal tree exists and reverse-engineer its structure |
| 17:08 | Lemma 1: the least likely symbol is deepest |
| 24:22 | Lemma 2: the second least likely symbol is also deepest |
| 32:16 | Corollary: the two can be siblings |
| 34:36 | Contract the pair and recurse |
| 37:15 | Key lemma: the contracted tree is optimal for the subproblem |
| 51:07 | Walkthrough on the running example |
| 1:01:07 | The Kraft inequality |
| 1:06:07 | Theorem: |
| 1:13:03 | Encoding pairs of symbols to amortize the to |
Prefix codes
A prefix code is a function such that for distinct symbols , neither is a prefix of nor the reverse.
This is stronger than requiring distinct codewords. For example is not a prefix code, since is a prefix of .
Tree representation
Lay the codewords out as a binary tree: walk left for 0 and right for 1 from the root, and each symbol corresponds to the path to some node.
The prefix condition is equivalent to: every symbol sits at a leaf, with no other symbol below it. If a symbol appeared at an internal node, its codeword would be a prefix of every descendant's codeword.
Conversely, any binary tree whose leaves are labelled with the symbols (some branches may be missing, but every internal node has at most two children) yields a prefix code.
Why decoding is unique
Given a bit stream, start at the root and descend one bit at a time. On reaching a leaf, emit that symbol and return to the root.
Uniqueness follows from the prefix condition. Suppose two parsings disagree at some position: one reads the next segment as symbol , the other as a codeword of different length. If is shorter, it is a proper prefix of ; if longer, is a proper prefix of . Both violate the condition.
This gives instantaneous decoding: no separators and no lookahead are needed; a symbol is emitted as soon as a leaf is reached.
The problem: minimize expected length
Let symbol have probability and codeword length . The objective is
Here is the average length per symbol. If length- blocks are treated as single symbols over an enlarged alphabet of size , the same algorithm applies and the expected length scales by . So solving the one-symbol problem suffices.
Throughout, probabilities are assumed distinct, and merged symbols are assumed not to tie with existing ones. Ties require only "at least tied" wording; the algorithm is unchanged.
Three structural lemmas
The strategy is not to construct the optimal tree directly but to assume one exists and derive what it must look like. The constraints turn out to be strong enough to determine the tree.
Every proof uses the same move: swap two symbols' positions. A swap leaves the set of codewords untouched, so prefix-freeness is preserved; only the expected length changes.
Lemma 1: the least likely symbol is deepest
Lemma. If has the smallest probability, then its codeword is at least tied for longest.
Proof. Suppose not. Let be a deepest symbol with . Swap the codewords of and , leaving all others fixed. Only two terms change:
By assumption and (with no ties), so .
The swap strictly shortens the code, contradicting optimality. Hence lies at the deepest level.
Lemma 2: the second least likely symbol is also deepest
Lemma. If has the second smallest probability, then is also maximal.
Proof, in two steps.
First, the parent of must have another child. If had only , detach and attach it to 's parent. Since carries no symbol (prefix-freeness), deleting it loses nothing, while 's codeword shortens by one, strictly improving — a contradiction.
Let be the symbol at 's other child, so .
Second, suppose . Swap the codewords of and . The same computation gives
Here and (since is second smallest and is not the smallest), so , again contradicting optimality.
Hence , and both sit at the deepest level.
Corollary: they can be made siblings
By the two lemmas, both and are deepest. The parent of has another child at the same depth. Swap the positions of and : depths are equal, so is unchanged, and now and share the parent .
Thus without loss of generality, the two least likely symbols are siblings in an optimal tree. This is what makes the contraction below legitimate.
Contraction and recursion
Building the subproblem
Delete and from the alphabet and add a new symbol with
leaving all other probabilities unchanged. This is still a valid distribution.
Do the same on the tree: remove the leaves and and turn their parent into a leaf labelled . The resulting tree is a prefix code on the new alphabet .
Key lemma: is still optimal
Lemma. If is optimal for the original problem, then is optimal for the reduced alphabet .
Proof. Suppose some tree is better, with expected length .
Expand the leaf holding in into a small subtree with and as children. This yields a valid prefix code on the original alphabet .
What is its expected length? The contributions of all symbols other than are unchanged. Wherever appeared, the code now continues one level deeper to reach or , so the expected length grows by exactly . The expanded length is therefore
The original tree is obtained from by the same expansion, so
Since , we get : a tree better than , a contradiction.
This lemma is the hinge of the algorithm: the optimum of the original problem can be recovered from the optimum of the subproblem. So contract repeatedly until two symbols remain; a two-symbol tree has only one shape (a root with two leaves), then expand back level by level.
Huffman's algorithm
Figure:The merged tree, the code table, and the average length 2.32。
Algorithm. Maintain a set of symbols with probabilities and a record of merges:
- Take the two symbols (or merged symbols) of smallest probability.
- Merge them into a new symbol whose probability is the sum, recording "left child, right child".
- Put it back and repeat until one symbol remains.
- Expand the merge record from the root, labelling left branches 0 and right branches 1.
Running example
Symbols and probabilities: , , , , , .
| Step | Merge | New probability | Remaining symbols |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | done |
Expanding back gives the code:
| Symbol | Probability | Codeword | Length |
|---|---|---|---|
| 0.40 | 0 | 1 | |
| 0.10 | 100 | 3 | |
| 0.05 | 1010 | 4 | |
| 0.07 | 1011 | 4 | |
| 0.18 | 110 | 3 | |
| 0.20 | 111 | 3 |
Prefix check: 0 is separated from every codeword starting with 1; are pairwise prefix-free (101 is not a codeword, but 1010 and 1011 branch below it, which is allowed).
The expected length is
The entropy of the source is
So , inside the promised interval.
Decoding example: the stream 1010 0 110 walks 1→0→1→0 to a leaf, giving ; back at the root, 0 gives ; then 110 gives . The message is . We never stop at 101, because 101 is not a leaf.
The Kraft inequality
Theorem (Kraft). Given positive integers , a binary tree with leaves at exactly these depths exists if and only if
Necessity. A node at depth occupies of the total "mass": the root has mass 1, and each level splits its mass equally between two children. Leaves occupy disjoint mass, so the total is at most 1.
Sufficiency. Sort the depths increasingly and place leaves at the shallowest available positions; a leaf at depth consumes all mass below it. The inequality guarantees that space remains when each leaf is placed. Note: the lecture defers the full construction to recitation; this is only a sketch.
Performance:
Lower bound
For any prefix code, Kraft's inequality gives . Set ; then is a probability distribution. Gibbs' inequality (nonnegativity of relative entropy) gives
The last step uses
So , and since we have , hence : no prefix code can beat entropy, matching Shannon's converse from the previous lecture.
Upper bound
Propose the codeword lengths
First check Kraft. Since , we have , so
A tree with these depths therefore exists. Its expected length satisfies
Huffman's code is optimal among all prefix codes, so . Together,
Amortizing the
Encoding one symbol at a time costs at most one extra bit per symbol. Bundle two symbols into one: the alphabet becomes symbols and the source is still first order. Its entropy is
Huffman on pairs gives , i.e. per symbol. For blocks of length : , so the per-symbol gap is at most .
This improves Shannon's bound: Shannon's error was (possibly or ), while blocked Huffman reduces it to the constant 1.
What this lecture establishes
- A prefix code has no codeword a prefix of another; equivalently, all symbols sit at leaves of a binary tree.
- Symbol-by-symbol coding replaces an exponentially large table with a tree, giving unique and instantaneous decoding.
- Three exchange arguments fix the shape of an optimal tree: least likely and second least likely symbols are deepest, and can be made siblings.
- Contracting that pair into a symbol with summed probability preserves optimality, which justifies greedy merging.
- The Kraft inequality characterizes which length profiles are realizable.
- Huffman satisfies ; blocking amortizes the to .
Comprehension check
1. Why is prefix-code decoding unambiguous? Explain by assuming an alternative parsing.
Reference answer: Suppose two parsings disagree at some position: one reads the next segment as symbol , the other as a codeword of different length.
- If is shorter, it is a prefix of , violating prefix-freeness;
- if is longer, is a prefix of , also a violation.
So only one parsing is legal at every position. Distinctness of codewords alone would only prevent whole-message collisions; it would not allow splitting a stream on the fly.
2. Use an exchange argument to show that the least likely symbol must be deepest.
Reference answer: Let have the smallest probability and suppose its length is not maximal. Pick a deepest symbol , so . Swapping their codewords preserves prefix-freeness (only which symbol occupies which codeword changes), and the expected length changes by
Since and , , contradicting optimality. Hence is at the deepest level.
3. Why must the parent of have another child, and what role does this play?
Reference answer: If the parent had only , then carries no symbol (otherwise prefix-freeness fails). Detaching and attaching it to 's parent deletes , keeps a valid prefix code, and shortens 's codeword by one, strictly improving — a contradiction.
The consequence is that 's other child has the same depth as . That gives a symbol at 's depth to swap with the second least likely symbol , proving is also deepest; swapping into 's position then makes and siblings.
4. Let be optimal and its contraction. Prove is optimal for the subproblem, and explain why .
Reference answer: Suppose a better tree exists for the subproblem, with . Expand the leaf holding into a parent with children and ; this is a valid prefix code for the original alphabet.
The contributions of all symbols other than are unchanged. Where used to end, the code now descends one more level to reach or , so the expected length increases by exactly . The expanded length is .
Likewise comes from expanding , so . Then , giving a tree better than , contradicting optimality.
The identity means: contraction removes one level's contribution from the subproblem, and expansion adds it back.
5. Run Huffman's algorithm on , verify , and relate it to entropy.
Reference answer: The merges are , then , then , then , then .
Expanding back gives , , , , , with lengths . Hence
The entropy is , so holds. The gap is about , far below 1, because the probabilities are close to negative powers of two.
6. Use Kraft to show that is always realizable, and derive .
Reference answer: Since , we have , hence
Kraft guarantees the tree. Its expected length is
Huffman is optimal among prefix codes, so .
7. Why does pairing symbols halve the loss? What is the general statement for blocks of ?
Reference answer: After pairing, the alphabet has symbols with probabilities , and its entropy is
using in each sum. Huffman on pairs gives , so per symbol .
For blocks of length , entropy is and , so the per-symbol error is at most , tending to zero. This is how Shannon's becomes a constant 1.
8. Huffman's code is already optimal among prefix codes. Why might Shannon's theorem still be needed?
Reference answer: They answer different questions. Huffman gives an implementable, optimal prefix code, but optimality holds only within the class of symbol-by-symbol prefix codes. If arbitrary injective block codes are allowed (no prefix structure), a little more can be saved in principle, and Shannon's theorem describes that larger class with the value .
Huffman's bound also requires knowing the distribution and rebuilding the tree when it changes; Shannon's result does not depend on any algorithm and tells us whether further improvement is even possible. They are complementary: Huffman gives constructions, Shannon gives limits.
Relation to neighbouring lectures
The previous lecture proved entropy is the asymptotic limit for arbitrary block codes but gave an unimplementable construction; this lecture provides an implementable optimal prefix code and tightens the loss from to the constant 1.
The next lecture turns to noisy channels: transmitted bits may flip, so the goal changes from "shorter" to "more reliable". Shannon's second theorem uses random coding and typicality to show that below channel capacity the error probability can be driven arbitrarily low. The two lectures after that give concrete correction schemes: Hamming codes and Reed–Solomon codes.