Optimal prefix code Created 2026-09-24 Updated 2026-10-14
An optimal prefix code minimizes expected codeword length for a fixed source probability distribution. Here the source alphabet is finite, has symbols, and has for every symbol; each source symbol receives one codeword over the binary output alphabet . Its code tree puts the symbols at leaves. Reading the edges along the graph path from the root of a tree to a leaf produces its codeword, so the leaf depth in a code tree is exactly its codeword length. Thus
For unnormalized positive weights, minimize instead; the corresponding expected codeword length is . This connects the abstract optimization to storage or transmission: counts the bits charged when symbol occurs. Huffman coding attains this minimum; the Huffman sibling property and Huffman sibling contraction explain why. [ref]
For , a balanced code tree charges every symbol two bits, giving . The codeword lengths charge the most frequent symbol only one bit, giving . The choice concerns weighted cost, not just the greatest codeword length: increasing that maximum from two to three can improve the average.
The search over prefix codes looks infinite, but positivity reduces it to finitely many full binary trees with leaves. A vertex with one child can be suppressed to improve cost, and a full binary tree with leaves has internal vertices. There are consequently finitely many such shapes and symbol assignments, so the minimum exists. For four leaves, the only possible sorted codeword lengths in a full binary tree are and . Probability monotonicity of optimal prefix-code lengths assigns larger probabilities to shallower leaves, giving respective minimum costs and in this example. This is an independent small-instance check of the Huffman code.
These hypotheses matter. With zero weights, suppressing a subtree carrying only zero weight need not strictly improve cost, so an optimal prefix code need not have a full binary tree. A one-symbol source raises the convention of whether an empty codeword is allowed. Both cases are outside the original statement here. Encoding groups of symbols changes the source alphabet and the optimization problem; the minimum here concerns one source symbol per codeword.