Replacing every quaternary digit by its fixed two-bit representation preserves the prefix code property: a binary prefix between translated codewords would end at an even position and hence imply a quaternary prefix. Thus a translated quaternary Huffman code cannot beat binary Huffman coding in expected codeword length.
For the reverse bound, binary prefix code lengths give candidate quaternary lengths . Since , the Kraft inequality supplies such a quaternary prefix code. Optimality of quaternary Huffman coding and give . These quantities are expected codeword lengths for the same source probability distribution.
Short inputs can spend much of their size on Deflate block framing, the end-of-block symbol and, for dynamic blocks, Deflate Huffman coding descriptions. A repeated phrase is useful only if its Deflate backreference costs less than the Deflate literal bytes it replaces. Huffman coding adapts instruction costs; it does not make either references or code descriptions free.
For an exact expansion example, take the 256 bytes with values , each appearing once. A single fixed block containing only Deflate literal bytes costs bits, or 272 bytes after final packing. One stored block starting at a byte boundary instead costs five overhead bytes plus the 256 data bytes, or 261 bytes. Both exceed the 256-byte input; these counts follow the specified layouts and are not measurements of an encoder's automatic choice. The example illustrates universal lossless shortening is impossible.[ref]
The following independent experiment obtains an actual raw Deflate stream using the standard library's zlib module, then checks exact recovery. Negative wbits selects raw framing; the three lines of compressed-data handling make no assumptions about which Deflate backreferences the library selects.[ref]
import zlib
data = b"ABCABCABCABC"
encoder = zlib.compressobj(level=6, wbits=-15)
packed = encoder.compress(data) + encoder.flush()
assert zlib.decompress(packed, wbits=-15) == data
print(len(data), len(packed), packed.hex())
The printed bytes describe this library run. Exact roundtrip recovery is the check; a particular compressed length or instruction choice is not a guarantee for other inputs or library versions.
Consider a binary Markov source with fair initial bit and flip probability . Its exact -symbol information entropy is . At ,
This includes the uncertainty of the initial bit; the entropy rate itself is bits per symbol. The finite-block difference is .
For any finite block distribution, the entropy lower bound for prefix codes gives expected codeword length , while Shannon coding achieves . These bounds apply to each block as one source symbol, without requiring consecutive blocks to be independent. Here Huffman coding on all possible 16-symbol words gives the independently calculated value bits per block, or bits per symbol. The noninteger value is an expected value; each actual codeword has an integer length. As the block length grows, the prefix code bounds squeeze towards the entropy rate when an optimal code is used.
Figure 1.
Fair marginal bits can have a lower entropy rate, with a finite-block initial cost
. The left panel shows the exact binary entropy for the symmetric binary Markov source; each individual symbol still has one bit of information entropy. Both near-persistence and near-alternation make the next symbol predictable. The right panel uses and plots , rather than literal fractional codeword lengths. The Huffman coding point is the exact expected length over all 16-symbol words. Details.
An entropy rate below one does not allow every word to fit into a shorter fixed binary word with zero error. For , all binary words are possible, so an injective fixed-length code needs at least bits. Compression instead exploits variable codeword lengths, or the vanishing-error convention in reliable source encoding at a rate. These are different guarantees.
Huffman code Created 2026-10-14 Updated 2026-10-25
A Huffman code is the prefix code returned by Huffman coding; the algorithm chooses a code tree, while the code specifies the actual symbol-to-codeword assignment. For the probability distribution in symbol order , the illustrated binary tree gives
The codeword lengths are . This is a prefix code because no complete codeword is an initial segment of another complete codeword. Thus a decoder can start at the root of a tree, follow one edge per bit, emit a symbol on reaching its leaf, then restart at the root of a tree. In particular, 011010111 splits as 0 | 110 | 10 | 111 and decodes to . No separators are transmitted: the leaf tells the decoder where a codeword ends.
The expected codeword length is
bits per source symbol. Four symbols would require bits each if all codewords had the same length, so this Huffman code saves bit per symbol on average, or of that fixed-length payload. A particular message can grow: uses nine bits here instead of eight. These lengths count the encoded symbols only; transmitting a code description or message framing can add further cost.
The Kraft inequality is saturated by this Huffman code:
Its Shannon entropy is
bits per symbol, slightly below the expected codeword length . The entropy lower bound for prefix codes applies to every binary prefix code for this probability distribution. It need not be attainable with integer codeword lengths for individual symbols; Huffman coding reaches the best mean within that class. [ref]
A Huffman code need not be unique. In the first example, the tied and weights can exchange their edge labels, changing codewords but preserving their codeword lengths. Ties can also change the lengths themselves. For a second probability distribution , first merge to weight . The next merge can join with either or the subtree, since both have weight . Joining with permits , with all lengths . Joining with the subtree permits , with lengths . Both are optimal prefix codes with expected codeword length : for the latter, . Tie choices can change the code tree without changing the minimum mean.
// Target: algebra.bigb
Replace sibling leaves in a code tree labelled by their common parent in a rooted tree, now a leaf labelled of weight . All other codewords stay fixed; each of loses one bit. For any such code tree and the contracted code tree , their weighted costs satisfy
If have two least weights, the Huffman sibling property gives an optimal prefix code containing this pair. Its contracted prefix code must be optimal for the reduced weights : any cheaper reduced prefix code could be expanded at by appending , giving a cheaper original prefix code. Conversely, expanding any optimal reduced prefix code adds precisely and attains the original minimum. This is optimal substructure, the justification for repeating the merge in Huffman coding. [ref]
In the exchange diagram, contract to weight at leaf depth in a code tree . The reduced expected codeword length is bits; expanding restores bits. For , the reduction leaves one symbol: allow its temporary codeword to be empty, of cost zero, so expansion gives the two one-bit codewords. This convention is only the terminal reduced problem; the original source has at least two symbols.
Huffman sibling property Created 2026-09-24 Updated 2026-10-14
For a finite source alphabet of symbols with positive weights , choose any two least weights, breaking ties arbitrarily. There exists an optimal prefix code over the binary output alphabet whose chosen symbols occupy sibling leaves in a code tree at maximum leaf depth in a code tree. Weights may be counts or probabilities: dividing every weight by gives the same minimizers. The existence statement is what makes the first merge of Huffman coding safe. It does not say that every optimal prefix code already has the chosen pair together.[ref]
An exchange makes the idea tangible. Take probabilities . The prefix code , , , has expected codeword length bits. Exchange only the symbols at their existing leaves: the available codewords and code tree shape stay fixed, but the codeword lengths in symbol order become . The new expected codeword length is bits, and the two least probabilities, those of , now occupy deepest sibling leaves in a code tree. The saving is bit per source symbol.
Figure 1.
Exchanging two leaf labels reduces expected length from 2.5 to 1.9 bits; contracting the least-probability siblings leaves cost 1.6
. Details.
Here is the short proof outline. An optimal prefix code with positive weights has a full binary tree as its code tree: suppressing a vertex with only one child shortens every codeword in that subtree and strictly reduces cost. A deepest leaf therefore has a leaf as its sibling, giving the deepest sibling property of an optimal prefix code. Put the two chosen least weights at these positions by successive exchanges of leaf labels. Moving a weight from leaf depth in a code tree to a deepest position , occupied by , changes the weighted sum by
Fix one chosen weight there, then move the other into the neighbouring deepest position; if it is already there, no exchange is needed. The prefix code condition survives because the set of codewords is unchanged. Starting from an optimal prefix code, the cost cannot decrease below the minimum, so these exchanges preserve optimality. Strictly unequal weights at unequal depths would give a strict decrease, explaining probability monotonicity of optimal prefix-code lengths. Equal weights or equal depths allow cost-neutral exchanges. [ref]
Nonunique optimal prefix code Created 2026-09-24 Updated 2026-10-14
An optimal prefix code can be nonunique in several different senses. Exchanging the labels on the outgoing edges of an internal vertex changes codewords while preserving every symbol's codeword length, the code tree shape, and expected codeword length. This freedom exists even with strictly unequal probabilities. Exchanging equal-probability symbols between leaves also preserves expected codeword length; if their leaf depths in a code tree differ, their individual codeword lengths change, though the set of leaf depths does not. For example, three equiprobable symbols have optimal codeword lengths : any of the three can receive the one-bit codeword.[ref]
Ties between weights of entire subtrees during Huffman coding can go further and change the code tree shape and its collection of codeword lengths. Take and first merge , creating weight . Next, of weight can merge either with or with the subtree, both of weight . The two resulting prefix codes are
For the second prefix code, bits. Both merge sequences add weights , whose sum is . Enumerating the full binary trees with four leaves also proves optimality independently: costs , while the least cost of is again . The two code trees cannot be obtained from each other merely by relabelling leaves or exchanging edge labels: their collections of leaf depths in a code tree differ.
Figure 1.
A tie between a symbol and a merged subtree gives two optimal prefix trees, with depths 2,2,2,2 and 1,2,3,3
. Details.
The quantifier in the Huffman sibling property is visible here too. Choose as two least-probability symbols. In the displayed balanced optimal prefix code, they are not sibling leaves in a code tree. Exchanging , which have equal probabilities, produces another balanced optimal prefix code in which are deepest sibling leaves in a code tree. Thus the proof supplies an optimal representative with the chosen pair together. It does not force that labelling on every optimum. An implementation can make its tie choices and edge assignments deterministic when encoder and decoder need to reproduce the same codewords; optimal mean length alone does not specify them.
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.
Optimal source code Created 2026-10-06 Updated 2026-10-14
For a fixed source distribution and code alphabet, an optimal uniquely decodable code minimizes expected codeword length. Huffman coding gives an optimal binary prefix code, and the equivalence of attainable uniquely-decodable and prefix-code lengths gives the same minimum for both classes.
The entropy is
To construct a Huffman code, work with integer weights . Merge the two twos to make four. Of the remaining weights , merge three with the original four to make seven, and merge the new four with five to make nine. Finally merge seven with nine. Resolving the tie in this way gives, for example,
This is a prefix code and Huffman's optimality theorem makes it optimal. Its expected length is
Different choices at a tied merge can give different optimal codewords with the same expected length.
Figure 1.
An optimal five-symbol Huffman tree
. Edge labels give the binary digits, leaf labels give the source symbols and their probabilities, and interior labels give total descendant probability. Details.
Let . The Huffman encoder emits an average of binary digits per minute. Shannon's noisy-channel coding theorem states that for a discrete memoryless channel of capacity , every information rate strictly below bits per use is achievable with error probability tending to zero as block length grows; rates above are not achievable for unrestricted messages.
Thus a channel code carrying the Huffman bitstream reliably with buffering and arbitrarily long blocks can be chosen whenever
The strict inequality supplies positive coding and buffering slack. Huffman's expected-length bound is for a nontrivial finite source. Therefore the simpler bound is sufficient without knowing its exact Huffman lengths.
Distinguish this bitstream construction from the absolute source-channel limit. The noiseless source coding theorem permits long source blocks to be compressed to any rate above bits per source symbol, with arbitrarily small overhead. Together with channel coding, this gives the sharper limiting requirement ; is impossible by the source-channel converse. Further compression can exploit redundancy remaining in a single-symbol Huffman stream, so need not be the universal minimum channel symbol rate. At a positive-entropy source cannot be sent reliably at a finite rate.
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.
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.
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.
The binary Huffman coding algorithm repeatedly merges the two currently least probable symbols into one meta-symbol whose probability is their sum. After recursively constructing a code for the smaller alphabet, append and to the meta-symbol's codeword to obtain codewords for the merged pair. The result is a binary prefix code.
To prove optimality, begin with an optimal prefix-code tree. It may be taken to be full, since an internal vertex with one child can be suppressed and all codewords below it shortened. Two leaves of maximum depth are siblings. By exchanging labels, without changing lengths, assign two least probable symbols to such a sibling pair: moving a smaller probability to a no-shorter codeword cannot increase the expected length. Contracting this pair to one leaf replaces their contribution by plus the constant . If the contracted code were not optimal for the reduced alphabet, replacing it by a better one and then expanding the merged leaf would improve the original code. Mathematical induction on the number of symbols now proves that the Huffman construction minimizes expected word length.
In Shannon-Fano coding, a symbol of probability is assigned length
and codewords of those lengths are chosen in lexicographic probability intervals; the Kraft inequality guarantees that a binary prefix code exists. Huffman coding repeatedly merges the two least probable current symbols, builds a binary tree from the resulting merges, and labels its two branches by zero and one. Reading from the root to each leaf gives an optimal prefix code.