For the nontrivial case , every and
The probability ordering makes . At a dyadic number, choose the terminating binary expansion followed by zeros. Let be the first bits of , and let
be its binary cylinder interval.
Suppose and were a prefix of . Since , the numbers and would have the same first bits, so both would lie in . In particular . But
a contradiction. A later word cannot be a shorter prefix of an earlier word because the lengths are nondecreasing; equal-length coincidences were also excluded. Thus the cumulative Shannon code is a prefix code.
The ceiling inequalities give
Multiply by and sum to obtain
For a one-symbol deterministic source the displayed construction assigns the empty word and gives . This zero-bit convention is valid when the number of source emissions is supplied separately. It is not an unframed uniquely decodable code: concatenating different numbers of empty words gives the same bit string. If positive-length unframed words are required, the shortest deterministic code has length , so the strict upper bound requires the nontrivial-source assumption.
An instantaneous code can decode each symbol as soon as its final bit arrives, without waiting for later bits. Equivalently it is prefix-free: no codeword is a proper prefix of another, and different symbols receive different codewords.
For nonempty codewords, decoding greedily from the start of the bit string identifies the first codeword unambiguously; repeating identifies the whole sequence. Thus an instantaneous code is uniquely decodable under the ordinary nonempty-word convention.
The codeword lengths are integers. For necessity, take and view codewords as nodes of the binary tree. A codeword of length has descendant words at depth . Prefix-freeness makes these descendant sets disjoint, so
For sufficiency, reorder the lengths nondecreasingly. Assign words successively. At depth , words extending previously assigned codewords number
The asserted inequality, even after dropping the later nonnegative terms, gives
Thus at least one depth- word does not extend an earlier word. Choose it. Since lengths are nondecreasing, it cannot be a proper prefix of a shorter earlier word, and equal-length duplicates have been excluded. Induction constructs the required code. Therefore Kraft inequality is necessary and sufficient:
The displayed prefix code has expected codeword length ternary digits per source symbol. Instead assign
This is a ternary prefix code: the first two codewords end at distinct tree children of the tree root, and the other two start with and end at distinct tree children below it. No codeword is a prefix of another. Its expected codeword length is
The reduction is trit per source symbol, which already disproves optimality of the displayed code. The ternary Huffman coding construction below will produce this same improved code tree.
Figure 1.
An original ternary prefix tree with expected length 1.25 ternary digits per source symbol
. Details.
First assume a full-support finite distribution, as stated above. Let be the largest codeword length and take a tree leaf at depth . Every existing tree child of its tree parent must also be a tree leaf: an internal tree child would have a descendant deeper than . If the chosen tree leaf were its tree parent's only tree child, moving its symbol to that tree parent would shorten its codeword by one, preserve the prefix code property, and reduce expected codeword length by its positive probability. That contradicts optimality. The tree parent therefore has at least two tree children, both tree leaves. A second codeword has the same first digits and a different last digit, proving the required deepest sibling codeword property for a ternary prefix code.
For the literal wording allowing zero probabilities, take and the prefix code . Its expected codeword length is one, which is minimal: with more than one message an empty codeword is impossible, so the positive-probability message must have length at least one. Yet the deepest tree leaf has no sibling codeword. Thus positivity or an additional convention removing redundant zero-weight branches is needed.
Exchange the two complete codewords while leaving the code tree unchanged. The prefix code property is preserved because the set of codewords is unchanged. If but , the change in expected codeword length is
contradicting optimality. Hence implies . This probability monotonicity of optimal prefix-code lengths is valid even if some probabilities are zero; equal probabilities impose no order.[ref]
With a full-support finite distribution, suppose two distinct tree parents at depth each have exactly two tree children, both tree leaves. Move one tree leaf from the second pair into the vacant third tree child slot of the first tree parent. Its length remains , so this relocation does not change expected codeword length. The second tree parent now has a single tree child, which is a tree leaf. Replace that remaining tree child's codeword by the tree parent's word. This preserves the prefix code property and shortens a positive-probability codeword by one. Expected codeword length strictly decreases, a contradiction. Thus there is at most one deepest pair with exactly two sibling codewords.
If zero-probability symbols are retained without a reduction convention, the claim can fail. The probability mass function with prefix code has the optimal expected codeword length one, yet contains the two deepest pairs and . The contraction would only shorten a zero-probability word.
Assume a full-support finite distribution. The preceding structural arguments show that every internal vertex has three tree children, except possibly one tree parent at depth with two tree children. Let and count these two kinds of internal vertex. Part iv gives ; no vertex has one tree child.
A finite rooted tree with tree leaves has edges, while counting outgoing edges gives . Equating the counts yields
For an odd integer , the right side forces to be an even integer. Since it is at most one, . Thus no deepest pair has only two sibling codewords, and the optimal code tree is a full ternary tree. This leaf-count identity also directly proves that a full ternary tree has an odd number of tree leaves.
Again the unrestricted zero-weight version is false: is an optimal prefix code for , with odd integer , but its two deepest tree leaves form a two-sibling pair. There is no contradiction with the proof because its tree root has only two tree children, which the full-support finite distribution assumption would forbid above the deepest level.
Let again denote the largest codeword length, and assume a full-support finite distribution. The missing-branch exchange from part iii forces every internal vertex at depth at most to have three tree children. At depth , all tree children are tree leaves. Part ii rules out one tree child there; the hypothesis that there is no pair of two deepest sibling codewords rules out two tree children. Thus each such tree parent also has three tree children. Every internal vertex has exactly three tree children, which is a full ternary tree, called semi-complete in this paper. The same last-level argument covers .
Without the assumption of a full-support finite distribution the implication is false: for , the optimal prefix code has no deepest pair of two sibling codewords, but its code tree contains vertices with a single tree child. Empty unused tree children are not vertices of the code tree.
For an odd integer , ternary Huffman coding repeatedly merges three smallest weights.
Start with one tree leaf for each source symbol, weighted by its probability. While more than one weighted object remains, choose the three objects with least weights, create their common tree parent with weight equal to their sum, and replace the three by that tree parent. Newly created tree parents participate in subsequent choices. Each merge reduces the number of objects by two; an odd number of objects therefore reaches three and then one, never an unmergeable pair. The final object is the tree root of the code tree.
Label the three outgoing edges at each internal vertex by in any order. The digits along the root-to-leaf graph path give each symbol's codeword. Tree leaves cannot be ancestors of other tree leaves, so this is a prefix code. Ties can be resolved arbitrarily. The expected codeword length is measured in trits, and equals the sum of all merge weights, because each merge adds one digit to every codeword below it.
The structural reason for merging three is that the positive-weight, odd-leaf case has a full ternary tree. Its deepest sibling codeword triple can receive the three least weights by exchanging tree leaf labels, and contracting that triple reduces the problem by two symbols. This explains the recursive construction; a separate optimality proof is not required here.
First, the binary translation of a quaternary prefix code is still a prefix code: every translated codeword length is even, and a binary prefix relation would split into complete two-bit blocks, giving a prefix relation between the original quaternary codewords. Binary Huffman coding is optimal among binary prefix codes, so
For the other direction, let and round these binary codeword lengths to quaternary lengths . The Kraft inequality gives
The quaternary converse of the Kraft inequality supplies a quaternary prefix code with lengths . Optimality of the quaternary Huffman code then implies
Thus binary translation of an optimal quaternary code costs at most one extra bit per source symbol:
The quaternary Huffman code uses the usual adjustment of adding zero-weight dummy leaves when needed. If the alphabet has one symbol, both optimal codes may use the empty codeword, giving the trivial endpoint.
A realized message has self-information . The average information per source message is its Shannon entropy,
The average reaches bits per message at . Individual rare realizations can have larger self-information; this bound concerns the average.
The given strings form a prefix code with lengths and . To attain the entropy bound without redundancy, the resulting long bit stream must carry one bit of information per bit: unbiased bits with no predictable dependence. For an independent source, the dyadic source matched to a complete prefix code has
These probabilities make the encoded stream equivalent to parsing independent fair bits using the code tree. Its expected codeword length and source entropy agree:
Here “optimal” means attaining the Shannon bound. If it means only an optimal prefix code among symbol-by-symbol binary prefix codes, the probabilities are not unique: for three positive-probability symbols, this tree is optimal whenever is a largest probability. Huffman coding need not attain entropy exactly for nondyadic probabilities.
Concatenating the specified source-message encodings gives
Pack consecutive bits in pairs, rather than allocating a fresh Bell pair to each variable-length source word:
Under the mapping in part 1, transmit
The block uses six message-bearing qubit transmissions and six preshared Bell pairs. Source-message boundaries are recovered by parsing the decoded prefix bit stream.
Shannon-Fano coding orders symbols by decreasing probability and recursively splits each consecutive block into two groups with probability totals as close as possible, appending bits zero and one. Huffman coding instead repeatedly merges the two least probable nodes, constructs a binary tree upwards, and then assigns the branch bits. Both yield prefix codes, so a concatenation can be decoded without separators; Huffman coding minimizes expected length among binary prefix codes.
For the specified probabilities, the first Shannon-Fano coding split is of mass versus the remaining mass . Split the latter into of mass and of mass , and then split off . One resulting code is
Its expected word length is .
The Huffman coding merges are , , , and . Reading the resulting tree gives the same code lengths , and it may give exactly the displayed code if the branch bits are chosen accordingly. Its expected length is also bits. The methods agree here; their agreement on this particular distribution is not a claim that the two procedures always coincide.
Take , as required for the lower bound in this part. A binary Huffman code has a full binary tree: every merge has two children, and all codewords are leaves. More generally an optimal prefix code for positive-probability symbols cannot have an internal vertex with only one child, since suppressing that vertex shortens its descendant codewords and reduces the expected length.
Choose a leaf of maximum depth . Its sibling must also be a leaf, since an internal sibling would have a descendant deeper than . These two leaves give the deepest sibling property of an optimal prefix code, and there are only leaves altogether. Therefore
For the degenerate singleton alphabet, an empty codeword suffices and ; the stated lower bound consequently excludes .
If all leaves of a full binary tree have depth , all binary paths of length end in leaves. Thus it has exactly leaves and . Equivalently, equality in the Kraft inequality gives .
Conversely, when a complete depth- tree is a prefix code with mean length . For any prefix lengths , convexity gives
so . The complete tree is optimal. A Huffman code attains this optimum, and equality in the strictly convex first inequality forces all its lengths to equal . Hence, for ,
This also proves that ties in the Huffman construction do not change the conclusion.
For Shannon-Fano coding, order the symbols by decreasing probability and recursively split each current list into two contiguous groups with total probabilities as close as possible. Label the two branches and ; the path to a symbol is its prefix code word. Here the first split is of weight against of weight . The latter splits into and , each of weight . One answer is
For Huffman coding, repeatedly merge the two least-probable nodes and then read the resulting binary tree from the root. Merge to weight , merge this node with to weight , and merge with . The same displayed prefix code results. Its mean length is . Choices at ties and exchange of binary labels yield other equivalent codes. Huffman coding minimizes mean length among binary prefix codes; the top-down Shannon-Fano construction does not have that general optimality guarantee.
The procedure in part (i) sometimes needs five tests, for items one or two. A binary decision tree of height has at most leaves, so distinguishing ten possibilities requires .
A prefix code attaining this worst-case bound is
Use the same subset-testing rule. The minimum worst-case number is four, so the expected-optimal procedure is not worst-case optimal. This four-test procedure has expectation , illustrating the small cost of imposing the smaller maximum depth.
There is a genuinely different optimal procedure. Exchange the codewords assigned to items three and four. Both have code length four, so each item's length, and hence the expected number of tests , remains unchanged. The first tested subset now contains item three instead of item four, so this changes the tested groups rather than merely reversing the names of the two test outcomes. The new prefix code still identifies every item uniquely and retains the minimum Huffman coding expectation.
Each test divides the current candidate set into a tested subset and its complement: failure places the defective item inside the subset, whereas success places it outside. A sequence of tests is therefore a binary decision tree, and minimizing its expected depth is the Huffman coding problem with weights .
Combine the smallest two current weights repeatedly. One choice of merges is , , , , , , , , . It gives this explicit prefix code:
At any node, test the candidate items whose next code digit is one. Assign failure to digit one and success to digit zero, and repeat until only a single codeword remains. This specifies every test, including the first subset . Huffman coding minimizes the weighted codeword lengths, so the optimal expected number is
The sum of the successive merged weights is another check on the numerator .
The Shannon entropy, in bits, is
For a prescribed alphabet distribution and code alphabet, an optimal code is a uniquely decodable code minimizing expected codeword length. Huffman coding produces an optimal binary prefix code, and its minimum is also the minimum among binary uniquely decodable codes.
Two optimal binary prefix codes, listing words in the order , are
Their length vectors are and , and both have expected length bits. To verify optimality rather than just equal length, run Huffman coding. First combine into a node of weight . Among the resulting three weight- nodes, combining and then combining the remaining weight- node with one weight- node gives the first length vector. Instead combine with the node, then combine that weight- node with , and finally with ; this gives the second. Each step combines two smallest current weights, so both constructions are Huffman coding trees. Ties therefore allow different optimal length profiles.