Recent from talks
Nothing was collected or created yet.
Huffman coding
View on Wikipedia
| Char | Freq | Code |
|---|---|---|
| space | 7 | 111 |
| a | 4 | 010 |
| e | 4 | 000 |
| f | 3 | 1101 |
| h | 2 | 1010 |
| i | 2 | 1000 |
| m | 2 | 0111 |
| n | 2 | 0010 |
| s | 2 | 1011 |
| t | 2 | 0110 |
| l | 1 | 11001 |
| o | 1 | 00110 |
| p | 1 | 10011 |
| r | 1 | 11000 |
| u | 1 | 00111 |
| x | 1 | 10010 |
In computer science and information theory, a Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression. The process of finding or using such a code is Huffman coding, an algorithm developed by David A. Huffman while he was a Sc.D. student at MIT, and published in the 1952 paper "A Method for the Construction of Minimum-Redundancy Codes".[1]
The output from Huffman's algorithm can be viewed as a variable-length code table for encoding a source symbol (such as a character in a file). The algorithm derives this table from the estimated probability or frequency of occurrence (weight) for each possible value of the source symbol. As in other entropy encoding methods, more common symbols are generally represented using fewer bits than less common symbols. Huffman's method can be efficiently implemented, finding a code in time linear to the number of input weights if these weights are sorted.[2] However, although optimal among methods encoding symbols separately, Huffman coding is not always optimal among all compression methods – it is replaced with arithmetic coding[3] or asymmetric numeral systems[4] if a better compression ratio is required.
History
[edit]In 1951, David A. Huffman and his MIT information theory classmates were given the choice of a term paper or a final exam. The professor, Robert M. Fano, assigned a term paper on the problem of finding the most efficient binary code. Huffman, unable to prove any codes were the most efficient, was about to give up and start studying for the final when he hit upon the idea of using a frequency-sorted binary tree and quickly proved this method the most efficient.[5]
In doing so, Huffman outdid Fano, who had worked with Claude Shannon to develop a similar code. Building the tree from the bottom up guaranteed optimality, unlike the top-down approach of Shannon–Fano coding.
Terminology
[edit]Huffman coding uses a specific method for choosing the representation for each symbol, resulting in a prefix code (sometimes called "prefix-free codes", that is, the bit string representing some particular symbol is never a prefix of the bit string representing any other symbol). Huffman coding is such a widespread method for creating prefix codes that the term "Huffman code" is widely used as a synonym for "prefix code" even when such a code is not produced by Huffman's algorithm.
Problem definition
[edit]This article needs additional citations for verification. (December 2021) |

Informal description
[edit]- Given
- A set of symbols and for each symbol , the frequency representing the fraction of symbols in the text that are equal to .[6]
- Find
- A prefix-free binary code (a set of codewords) with minimum expected codeword length (equivalently, a tree with minimum weighted path length from the root).
Formalized description
[edit]Input.
Alphabet , which is the symbol alphabet of size .
Tuple , which is the tuple of the (positive) symbol weights (usually proportional to probabilities), i.e. .
Output.
Code , which is the tuple of (binary) codewords, where is the codeword for .
Goal.
Let be the weighted path length of code . Condition: for any code .
Example
[edit]We give an example of the result of Huffman coding for a code with five characters and given weights. We will not verify that it minimizes L over all codes, but we will compute L and compare it to the Shannon entropy H of the given set of weights; the result is nearly optimal.
| Input (A, W) | Symbol (ai) | a | b | c | d | e | Sum |
|---|---|---|---|---|---|---|---|
| Weights (wi) | 0.10 | 0.15 | 0.30 | 0.16 | 0.29 | = 1 | |
| Output C | Codewords (ci) | 010
|
011
|
11
|
00
|
10
|
|
| Codeword length (in bits) (ℓi) |
3 | 3 | 2 | 2 | 2 | ||
| Contribution to weighted path length (ℓi wi ) |
0.30 | 0.45 | 0.60 | 0.32 | 0.58 | L(C) = 2.25 | |
| Optimality | Probability budget (2−ℓi) |
1/8 | 1/8 | 1/4 | 1/4 | 1/4 | = 1.00 |
| Information content (in bits) (−log2 wi) ≈ |
3.32 | 2.74 | 1.74 | 2.64 | 1.79 | ||
| Contribution to entropy (−wi log2 wi) |
0.332 | 0.411 | 0.521 | 0.423 | 0.518 | H(A) = 2.205 |
For any code that is biunique, meaning that the code is uniquely decodeable, the sum of the probability budgets across all symbols is always less than or equal to one. In this example, the sum is strictly equal to one; as a result, the code is termed a complete code. If this is not the case, one can always derive an equivalent code by adding extra symbols (with associated null probabilities), to make the code complete while keeping it biunique.
As defined by Shannon (1948), the information content h (in bits) of each symbol ai with non-null probability is
The entropy H (in bits) is the weighted sum, across all symbols ai with non-zero probability wi, of the information content of each symbol:
(Note: A symbol with zero probability has zero contribution to the entropy, since . So for simplicity, symbols with zero probability can be left out of the formula above.)
As a consequence of Shannon's source coding theorem, the entropy is a measure of the smallest codeword length that is theoretically possible for the given alphabet with associated weights. In this example, the weighted average codeword length is 2.25 bits per symbol, only slightly larger than the calculated entropy of 2.205 bits per symbol. So not only is this code optimal in the sense that no other feasible code performs better, but it is very close to the theoretical limit established by Shannon.
In general, a Huffman code need not be unique. Thus the set of Huffman codes for a given probability distribution is a non-empty subset of the codes minimizing for that probability distribution. (However, for each minimizing codeword length assignment, there exists at least one Huffman code with those lengths.)
Basic technique
[edit]Compression
[edit]
| Symbol | Code |
|---|---|
| a1 | 0 |
| a2 | 10 |
| a3 | 110 |
| a4 | 111 |
The technique works by creating a binary tree of nodes. These can be stored in a regular array, the size of which depends on the number of symbols, . A node can be either a leaf node or an internal node. Initially, all nodes are leaf nodes, which contain the symbol itself, the weight (frequency of appearance) of the symbol and optionally, a link to a parent node which makes it easy to read the code (in reverse) starting from a leaf node. Internal nodes contain a weight, links to two child nodes and an optional link to a parent node. As a common convention, bit '0' represents following the left child and bit '1' represents following the right child. A finished tree has up to leaf nodes and internal nodes. A Huffman tree that omits unused symbols produces the most optimal code lengths.
The process begins with the leaf nodes containing the probabilities of the symbol they represent. Then, the process takes the two nodes with smallest probability, and creates a new internal node having these two nodes as children. The weight of the new node is set to the sum of the weight of the children. We then apply the process again, on the new internal node and on the remaining nodes (i.e., we exclude the two leaf nodes), we repeat this process until only one node remains, which is the root of the Huffman tree.
The simplest construction algorithm uses a priority queue where the node with lowest probability is given highest priority:
- Create a leaf node for each symbol and add it to the priority queue.
- While there is more than one node in the queue:
- Remove the two nodes of highest priority (lowest probability) from the queue
- Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
- Add the new node to the queue.
- The remaining node is the root node and the tree is complete.
Since efficient priority queue data structures require O(log n) time per insertion, and a tree with n leaves has 2n−1 nodes, this algorithm operates in O(n log n) time, where n is the number of symbols.
If the symbols are sorted by probability, there is a linear-time (O(n)) method to create a Huffman tree using two queues, the first one containing the initial weights (along with pointers to the associated leaves), and combined weights (along with pointers to the trees) being put in the back of the second queue. This assures that the lowest weight is always kept at the front of one of the two queues:
- Start with as many leaves as there are symbols.
- Enqueue all leaf nodes into the first queue (by probability in increasing order so that the least likely item is in the head of the queue).
- While there is more than one node in the queues:
- Dequeue the two nodes with the lowest weight by examining the fronts of both queues.
- Create a new internal node, with the two just-removed nodes as children (either node can be either child) and the sum of their weights as the new weight.
- Enqueue the new node into the rear of the second queue.
- The remaining node is the root node; the tree has now been generated.
Once the Huffman tree has been generated, it is traversed to generate a dictionary which maps the symbols to binary codes as follows:
- Start with current node set to the root.
- If node is not a leaf node, label the edge to the left child as 0 and the edge to the right child as 1. Repeat the process at both the left child and the right child.
The final encoding of any symbol is then read by a concatenation of the labels on the edges along the path from the root node to the symbol.
In many cases, time complexity is not very important in the choice of algorithm here, since n here is the number of symbols in the alphabet, which is typically a very small number (compared to the length of the message to be encoded); whereas complexity analysis concerns the behavior when n grows to be very large.
It is generally beneficial to minimize the variance of codeword length. For example, a communication buffer receiving Huffman-encoded data may need to be larger to deal with especially long symbols if the tree is especially unbalanced. To minimize variance, simply break ties between queues by choosing the item in the first queue. This modification will retain the mathematical optimality of the Huffman coding while both minimizing variance and minimizing the length of the longest character code.
Decompression
[edit]Generally speaking, the process of decompression is simply a matter of translating the stream of prefix codes to individual byte values, usually by traversing the Huffman tree node by node as each bit is read from the input stream (reaching a leaf node necessarily terminates the search for that particular byte value). Before this can take place, however, the Huffman tree must be somehow reconstructed. In the simplest case, where character frequencies are fairly predictable, the tree can be preconstructed (and even statistically adjusted on each compression cycle) and thus reused every time, at the expense of at least some measure of compression efficiency. Otherwise, the information to reconstruct the tree must be sent a priori. A naive approach might be to prepend the frequency count of each character to the compression stream. Unfortunately, the overhead in such a case could amount to several kilobytes, so this method has little practical use. If the data is compressed using canonical encoding, the compression model can be precisely reconstructed with just bits of information (where B is the number of bits per symbol). Another method is to simply prepend the Huffman tree, bit by bit, to the output stream. For example, assuming that the value of 0 represents a parent node and 1 a leaf node, whenever the latter is encountered the tree building routine simply reads the next 8 bits to determine the character value of that particular leaf. The process continues recursively until the last leaf node is reached; at that point, the Huffman tree will thus be faithfully reconstructed. The overhead using such a method ranges from roughly 2 to 320 bytes (assuming an 8-bit alphabet). Many other techniques are possible as well. In any case, since the compressed data can include unused "trailing bits" the decompressor must be able to determine when to stop producing output. This can be accomplished by either transmitting the length of the decompressed data along with the compression model or by defining a special code symbol to signify the end of input (the latter method can adversely affect code length optimality, however).
Main properties
[edit]The probabilities used can be generic ones for the application domain that are based on average experience, or they can be the actual frequencies found in the text being compressed. This requires that a frequency table must be stored with the compressed text. See the Decompression section above for more information about the various techniques employed for this purpose.
Optimality
[edit]Huffman's original algorithm is optimal for a symbol-by-symbol coding with a known input probability distribution, i.e., separately encoding unrelated symbols in such a data stream. However, it is not optimal when the symbol-by-symbol restriction is dropped, or when the probability mass functions are unknown. Also, if symbols are not independent and identically distributed, a single code may be insufficient for optimality. Other methods such as arithmetic coding often have better compression capability.
Although both aforementioned methods can combine an arbitrary number of symbols for more efficient coding and generally adapt to the actual input statistics, arithmetic coding does so without significantly increasing its computational or algorithmic complexities (though the simplest version is slower and more complex than Huffman coding). Such flexibility is especially useful when input probabilities are not precisely known or vary significantly within the stream. However, Huffman coding is usually faster and arithmetic coding was historically a subject of some concern over patent issues. Thus many technologies have historically avoided arithmetic coding in favor of Huffman and other prefix coding techniques. As of mid-2010, the most commonly used techniques for this alternative to Huffman coding have passed into the public domain as the early patents have expired.
For a set of symbols with a uniform probability distribution and a number of members which is a power of two, Huffman coding is equivalent to simple binary block encoding, e.g., ASCII coding. This reflects the fact that compression is not possible with such an input, no matter what the compression method, i.e., doing nothing to the data is the optimal thing to do.
Huffman coding is optimal among all methods in any case where each input symbol is a known independent and identically distributed random variable having a probability that is dyadic. Prefix codes, and thus Huffman coding in particular, tend to have inefficiency on small alphabets, where probabilities often fall between these optimal (dyadic) points. The worst case for Huffman coding can happen when the probability of the most likely symbol far exceeds 2−1 = 0.5, making the upper limit of inefficiency unbounded.
There are two related approaches for getting around this particular inefficiency while still using Huffman coding. Combining a fixed number of symbols together ("blocking") often increases (and never decreases) compression. As the size of the block approaches infinity, Huffman coding theoretically approaches the entropy limit, i.e., optimal compression.[7] However, blocking arbitrarily large groups of symbols is impractical, as the complexity of a Huffman code is linear in the number of possibilities to be encoded, a number that is exponential in the size of a block. This limits the amount of blocking that is done in practice.
A practical alternative, in widespread use, is run-length encoding. This technique adds one step in advance of entropy coding, specifically counting (runs) of repeated symbols, which are then encoded. For the simple case of Bernoulli processes, Golomb coding is optimal among prefix codes for coding run length, a fact proved via the techniques of Huffman coding.[8] A similar approach is taken by fax machines using modified Huffman coding. However, run-length coding is not as adaptable to as many input types as other compression technologies.
Variations
[edit]Many variations of Huffman coding exist,[9] some of which use a Huffman-like algorithm, and others of which find optimal prefix codes (while, for example, putting different restrictions on the output). Note that, in the latter case, the method need not be Huffman-like, and, indeed, need not even be polynomial time.
n-ary Huffman coding
[edit]The n-ary Huffman algorithm uses an alphabet of size n, typically {0, 1, ..., n-1}, to encode messages and build an n-ary tree. This approach was considered by Huffman in his original paper. The same algorithm applies as for binary () codes, but instead of combining the two least likely symbols, the n least likely symbols are grouped together.
Note that for n > 2, not all sets of source words can properly form a complete n-ary tree for Huffman coding. In these cases, additional placeholder symbols with 0 probability may need to be added. This is because the structure of the tree needs to repeatedly join n branches into one - also known as an "n to 1" combination. For binary coding, this is a "2 to 1" combination, which works with any number of symbols. For n-ary coding, a complete tree is only possible when the total number of symbols (real + placeholders) leaves a remainder of 1 when divided by (n-1).[1]
Adaptive Huffman coding
[edit]A variation called adaptive Huffman coding involves calculating the probabilities dynamically based on recent actual frequencies in the sequence of source symbols, and changing the coding tree structure to match the updated probability estimates. It is used rarely in practice, since the cost of updating the tree makes it slower than optimized adaptive arithmetic coding, which is more flexible and has better compression.[citation needed]
Huffman template algorithm
[edit]Most often, the weights used in implementations of Huffman coding represent numeric probabilities, but the algorithm given above does not require this; it requires only that the weights form a totally ordered commutative monoid, meaning a way to order weights and to add them. The Huffman template algorithm enables one to use any kind of weights (costs, frequencies, pairs of weights, non-numerical weights) and one of many combining methods (not just addition). Such algorithms can solve other minimization problems, such as minimizing , a problem first applied to circuit design.
Length-limited Huffman coding/minimum variance Huffman coding
[edit]Length-limited Huffman coding is a variant where the goal is still to achieve a minimum weighted path length, but there is an additional restriction that the length of each codeword must be less than a given constant. The package-merge algorithm solves this problem with a simple greedy approach very similar to that used by Huffman's algorithm. Its time complexity is , where is the maximum length of a codeword. No algorithm is known to solve this problem in or time, unlike the presorted and unsorted conventional Huffman problems, respectively.
Huffman coding with unequal letter costs
[edit]In the standard Huffman coding problem, it is assumed that each symbol in the set that the code words are constructed from has an equal cost to transmit: a code word whose length is N digits will always have a cost of N, no matter how many of those digits are 0s, how many are 1s, etc. When working under this assumption, minimizing the total cost of the message and minimizing the total number of digits are the same thing.
Huffman coding with unequal letter costs is the generalization without this assumption: the letters of the encoding alphabet may have non-uniform lengths, due to characteristics of the transmission medium. An example is the encoding alphabet of Morse code, where a 'dash' takes longer to send than a 'dot', and therefore the cost of a dash in transmission time is higher. The goal is still to minimize the weighted average codeword length, but it is no longer sufficient just to minimize the number of symbols used by the message. No algorithm is known to solve this in the same manner or with the same efficiency as conventional Huffman coding, though it has been solved by Richard M. Karp[10] whose solution has been refined for the case of integer costs by Mordecai J. Golin.[11]
Optimal alphabetic binary trees (Hu–Tucker coding)
[edit]In the standard Huffman coding problem, it is assumed that any codeword can correspond to any input symbol. In the alphabetic version, the alphabetic order of inputs and outputs must be identical. Thus, for example, could not be assigned code , but instead should be assigned either or . This is also known as the Hu–Tucker problem, after T. C. Hu and Alan Tucker, the authors of the paper presenting the first -time solution to this optimal binary alphabetic problem,[12] which has some similarities to Huffman algorithm, but is not a variation of this algorithm. A later method, the Garsia–Wachs algorithm of Adriano Garsia and Michelle L. Wachs (1977), uses simpler logic to perform the same comparisons in the same total time bound. These optimal alphabetic binary trees are often used as binary search trees.[13]
The canonical Huffman code
[edit]If weights corresponding to the alphabetically ordered inputs are in numerical order, the Huffman code has the same lengths as the optimal alphabetic code, which can be found from calculating these lengths, rendering Hu–Tucker coding unnecessary. The code resulting from numerically (re-)ordered input is sometimes called the canonical Huffman code and is often the code used in practice, due to ease of encoding/decoding. The technique for finding this code is sometimes called Huffman–Shannon–Fano coding, since it is optimal like Huffman coding, but alphabetic in weight probability, like Shannon–Fano coding. The Huffman–Shannon–Fano code corresponding to the example is , which, having the same codeword lengths as the original solution, is also optimal. But in canonical Huffman code, the result is .
Applications
[edit]Arithmetic coding and Huffman coding produce equivalent results — achieving entropy — when every symbol has a probability of the form 1/2k. In other circumstances, arithmetic coding can offer better compression than Huffman coding because — intuitively — its "code words" can have effectively non-integer bit lengths, whereas code words in prefix codes such as Huffman codes can only have an integer number of bits. Therefore, a code word of length k only optimally matches a symbol of probability 1/2k and other probabilities are not represented optimally; whereas the code word length in arithmetic coding can be made to exactly match the true probability of the symbol. This difference is especially striking for small alphabet sizes.[citation needed]
Prefix codes nevertheless remain in wide use because of their simplicity, high speed, and lack of patent coverage. They are often used as a "back-end" to other compression methods. Deflate (PKZIP's algorithm) and multimedia codecs such as JPEG and MP3 have a front-end model and quantization followed by the use of prefix codes; these are often called "Huffman codes" even though most applications use pre-defined variable-length codes rather than codes designed using Huffman's algorithm.
References
[edit]- ^ a b Huffman, D. (1952). "A Method for the Construction of Minimum-Redundancy Codes" (PDF). Proceedings of the IRE. 40 (9): 1098–1101. doi:10.1109/JRPROC.1952.273898.
- ^ Van Leeuwen, Jan (1976). "On the construction of Huffman trees" (PDF). ICALP: 382–410. Retrieved 2014-02-20.
- ^ Ze-Nian Li; Mark S. Drew; Jiangchuan Liu (2014-04-09). Fundamentals of Multimedia. Springer Science & Business Media. ISBN 978-3-319-05290-8.
- ^ J. Duda, K. Tahboub, N. J. Gadil, E. J. Delp, The use of asymmetric numeral systems as an accurate replacement for Huffman coding, Picture Coding Symposium, 2015.
- ^ Huffman, Ken (1991). "Profile: David A. Huffman: Encoding the "Neatness" of Ones and Zeroes". Scientific American: 54–58.
- ^ Kleinberg, Jon; Tardos, Eva (2005-03-16). Algorithm Design (1 ed.). Pearson Education. p. 165. ISBN 9780321295354. Retrieved 2025-01-26.
- ^ Gribov, Alexander (2017-04-10). "Optimal Compression of a Polyline with Segments and Arcs". arXiv:1604.07476 [cs.CG].
- ^ Gallager, R.G.; van Voorhis, D.C. (1975). "Optimal source codes for geometrically distributed integer alphabets". IEEE Transactions on Information Theory. 21 (2): 228–230. doi:10.1109/TIT.1975.1055357.
- ^ Abrahams, J. (1997-06-11). "Code and parse trees for lossless source encoding". Written at Arlington, VA, USA. Proceedings. Compression and Complexity of SEQUENCES 1997 (Cat. No.97TB100171). Division of Mathematics, Computer & Information Sciences, Office of Naval Research (ONR). Salerno: IEEE. pp. 145–171. CiteSeerX 10.1.1.589.4726. doi:10.1109/SEQUEN.1997.666911. ISBN 0-8186-8132-2. S2CID 124587565.
- ^ Karp, Richard M. (1961-01-31). "Minimum-redundancy coding for the discrete noiseless channel". IRE Transactions on Information Theory. 7 (1). IEEE: 27–38. doi:10.1109/TIT.1961.1057615.
- ^ Golin, Mordekai J. (January 1998). "A Dynamic Programming Algorithm for Constructing Optimal Prefix-Free Codes with Unequal Letter Costs" (PDF). IEEE Transactions on Information Theory. 44 (5) (published 1998-09-01): 1770–1781. Bibcode:1998ITIT...44.1770G. doi:10.1109/18.705558. S2CID 2265146. Retrieved 2024-09-10.
- ^ Hu, T. C.; Tucker, A. C. (1971). "Optimal Computer Search Trees and Variable-Length Alphabetical Codes". SIAM Journal on Applied Mathematics. 21 (4): 514. doi:10.1137/0121057. JSTOR 2099603.
- ^ Knuth, Donald E. (1998), "Algorithm G (Garsia–Wachs algorithm for optimum binary trees)", The Art of Computer Programming, Vol. 3: Sorting and Searching (2nd ed.), Addison–Wesley, pp. 451–453. See also History and bibliography, pp. 453–454.
Bibliography
[edit]- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. ISBN 0-262-03293-7. Section 16.3, pp. 385–392.
External links
[edit]Huffman coding
View on GrokipediaHistory and Background
Origins and Development
Huffman coding originated in 1951 when David A. Huffman, a graduate student at the Massachusetts Institute of Technology (MIT), developed the algorithm as a term paper for an electrical engineering course on information theory taught by Professor Robert M. Fano.[5] The assignment challenged students to devise an optimal method for constructing variable-length prefix codes to minimize redundancy in data representation, building on the need for efficient encoding in early computing and communication systems. Huffman, opting for the term paper over a final exam, spent months grappling with the problem and ultimately derived a greedy algorithm for building binary trees that assign shorter codes to more frequent symbols.[6] The work was influenced by foundational concepts in information theory established by Claude Shannon in his 1948 paper "A Mathematical Theory of Communication," which introduced entropy as a measure of information and the limits of lossless compression.[7] Additionally, Fano's own earlier efforts on prefix codes, including the Shannon-Fano coding method developed around 1949, provided a suboptimal but related approach that Huffman sought to improve upon during the course.[8] Huffman formalized and published his method in 1952 in the paper "A Method for the Construction of Minimum-Redundancy Codes" in the Proceedings of the Institute of Radio Engineers (now IEEE), where he proved its optimality for prefix codes under known symbol probabilities.[1] Although completed during his Sc.D. studies at MIT, the idea stemmed directly from the 1951 term paper rather than a formal thesis defense.[9] Through the 1960s and 1970s, Huffman coding evolved from a theoretical construct to a practical tool in data compression, particularly for telegraphic transmission and early digital storage systems where bandwidth and storage were limited.[9] Researchers adapted it for applications in telecommunications and space data processing, with implementations appearing in systems like those for efficient encoding of telemetry data by the late 1960s.[10] However, computational constraints delayed broader adoption until the 1980s, when personal computing hardware made dynamic and static Huffman encoding feasible for widespread use in file compression and multimedia standards.[5]Key Contributors and Publications
David A. Huffman (1925–1999) is recognized as the primary inventor of Huffman coding, a cornerstone algorithm in data compression and information theory. Born on August 9, 1925, in Ohio, he earned a bachelor's degree in electrical engineering from Ohio State University in 1944, followed by military service in the U.S. Navy until 1946. He then completed a master's degree at Ohio State in 1949 and a Sc.D. in electrical engineering from the Massachusetts Institute of Technology (MIT) in 1953, where his doctoral work laid the groundwork for the coding method.[11] After joining the MIT faculty in 1953, Huffman moved to the University of California, Santa Cruz in 1967, where he founded and chaired the computer science department until 1973, retiring in 1994. His contributions extended beyond coding to sequential circuit design and information theory education.[11] Robert M. Fano served as Huffman's Ph.D. advisor at MIT and played a pivotal role in the development of Huffman coding by assigning a term paper on optimal binary codes, which inspired Huffman's breakthrough solution. Fano, born in 1917, was a prominent information theorist who co-developed the precursor Shannon–Fano coding method in 1949, an approach to variable-length prefix codes that influenced Huffman's work but was suboptimal in achieving minimum redundancy.[12] Fano's earlier efforts built on probabilistic encoding ideas, emphasizing efficient representation of discrete sources.[12] Claude E. Shannon provided the foundational theoretical framework through his 1948 paper "A Mathematical Theory of Communication," which introduced entropy as a measure of information uncertainty and the source coding theorem establishing the lower bound on lossless compression rates. Huffman's algorithm directly realizes near-optimal codes approaching this entropy limit for prefix-free binary representations. Huffman's seminal publication, "A Method for the Construction of Minimum-Redundancy Codes," appeared in the Proceedings of the I.R.E. in September 1952 (vol. 40, no. 9, pp. 1098–1101). The paper outlines a systematic procedure for generating prefix codes that minimize the average codeword length weighted by symbol probabilities, using a bottom-up tree construction to ensure no code is a prefix of another while satisfying the Kraft inequality. It demonstrates that such codes achieve the theoretical minimum redundancy for discrete sources, surpassing earlier methods like Shannon–Fano in efficiency.[13] This work, originating from Huffman's MIT term paper, has garnered over 7,500 citations as of 2019, reflecting its enduring impact on compression algorithms and coding theory.[14] Fano further advanced information theory concepts in his 1961 book Transmission of Information: A Statistical Theory of Communication (MIT Press), which provides a comprehensive treatment of entropy, channel capacity, and source coding, including discussions of variable-length codes and their probabilistic foundations. The text, aimed at graduate students and engineers, incorporates Fano's research on discrete communication systems and helped popularize Huffman-style methods in broader electrical engineering contexts.[15] In recognition of his contributions, Huffman received the IEEE Information Theory Society's Golden Jubilee Award for Technological Innovation in 1998 for inventing the Huffman minimum-length lossless data-compression code, honoring its profound influence on digital systems. He also earned the IEEE Richard W. Hamming Medal in 1999 for his work on minimum-redundancy codes and asynchronous sequential circuits.[16][17]Core Concepts
Terminology and Notation
In Huffman coding, the source alphabet refers to a finite set of distinct symbols to be encoded, typically denoted as , where is the size of the alphabet.[13] Each symbol is associated with a probability from a known probability distribution , where and , representing the frequency or likelihood of occurrence of that symbol in the source output.[14] A codeword is a unique binary string assigned to each symbol , denoted as , with length (the number of bits in ). The average code length is then given by which measures the expected number of bits required to encode a symbol from the source.[14] The source entropy , defined as provides a lower bound on the achievable average code length for any uniquely decodable code.[13] Huffman codes are prefix-free, meaning no codeword is a prefix of any other codeword in the set , which ensures instantaneous decodability without lookahead.[13] This property also makes the code uniquely decodable, as the mapping from sequences of codewords back to the original symbols is one-to-one. Such codes are often represented using a binary tree, where the leaves correspond to the symbols , and the path from the root to a leaf—labeled by 0s and 1s along the edges—forms the codeword .[14] Unlike fixed-length codes, where every symbol is assigned a codeword of uniform length regardless of probability, Huffman coding employs variable-length codewords, assigning shorter codewords to more probable symbols (higher ) to minimize the average code length .[13] While the standard formulation assumes a binary alphabet for codewords (radix 2), the concepts extend to general radix- codes by using a -ary tree instead of binary.[14]Problem Formulation
Huffman coding seeks to assign variable-length binary codewords to symbols emitted by a discrete source in a way that minimizes the expected length of the encoded sequence, given the known probability distribution of the symbols, while ensuring the code is prefix-free to enable unambiguous decoding without delimiters. This approach reduces redundancy in data representation for efficient storage or transmission.[1] Formally, the problem is defined for a discrete memoryless source producing symbols from a finite alphabet with stationary probabilities satisfying . The objective is to determine integer codeword lengths for a prefix code that minimize the average codeword length subject to the Kraft inequality This constraint ensures the existence of a corresponding prefix code over a binary alphabet. The formulation assumes independent and identically distributed (i.i.d.) symbols from the discrete alphabet, with probabilities known a priori, and focuses on block coding of individual symbols rather than sequences.[1][18] The problem connects directly to fundamental limits in information theory, where the source entropy quantifies the minimum average information per symbol in bits. Shannon's noiseless source coding theorem establishes that an optimal prefix code achieves an average length bounded by , providing the theoretical foundation for the efficiency of Huffman codes in approaching this bound.[7]Basic Example
To illustrate the Huffman coding process, consider a simple source alphabet consisting of four symbols: A with probability 0.4, B with probability 0.3, C with probability 0.2, and D with probability 0.1.[19] These probabilities are sorted in descending order as A (0.4), B (0.3), C (0.2), D (0.1) to facilitate the construction.[19] The tree construction begins by combining the two symbols with the lowest probabilities, C and D, into a new internal node with combined probability 0.3; this node represents a subtree for C and D.[1] Next, the lowest probabilities are now the combined CD node (0.3) and B (0.3); these are merged into another internal node with probability 0.6.[1] Finally, this 0.6 node and A (0.4) are combined at the root with total probability 1.0.[1] The resulting binary tree can be described textually as follows: Root (1.0)
/ \
A (0.4) Subtree (0.6)
/ \
B (0.3) Subtree (0.3)
/ \
C (0.2) D (0.1)
Root (1.0)
/ \
A (0.4) Subtree (0.6)
/ \
B (0.3) Subtree (0.3)
/ \
C (0.2) D (0.1)
Algorithm Description
Tree Construction Procedure
The Huffman tree construction algorithm is a greedy procedure that builds an optimal prefix code tree for a set of symbols with given probabilities by iteratively merging the least probable nodes.[20] The process begins by sorting the symbols in descending order of their probabilities to facilitate initialization, though the core merging relies on selecting the lowest probabilities dynamically.[21] A priority queue, typically implemented as a min-heap, is used to efficiently manage the nodes ordered by their probabilities (or frequencies), ensuring that the two nodes with the smallest probabilities are always accessible.[22] The steps of the algorithm are as follows: First, create a leaf node for each symbol, assigning it the symbol's probability as its weight, and insert all these leaves into the priority queue. Then, while the queue contains more than one node, perform the following: extract the two nodes with the minimum weights (using extract-min operations), create a new internal node with a weight equal to the sum of the two extracted nodes' weights, set the extracted nodes as the left and right children of this new node, and insert the new node back into the priority queue. This merging continues until only one node remains, which becomes the root of the Huffman tree.[20][22] The following pseudocode outlines the procedure, assuming a priority queue supporting extract-min and insert operations:function buildHuffmanTree(symbols, probabilities):
initialize priority queue Q as empty min-heap (keyed by probability)
for i from 1 to n: // n symbols
create leaf node leaf_i with symbol symbols[i] and weight probabilities[i]
insert leaf_i into Q
while size of Q > 1:
node1 = extract-min(Q)
node2 = extract-min(Q)
create internal node [parent](/page/Parent) with weight = node1.weight + node2.weight
set node1 as left [child](/page/Child) of [parent](/page/Parent)
set node2 as right [child](/page/Child) of [parent](/page/Parent)
insert [parent](/page/Parent) into Q
return [root](/page/Root) of Q // the final tree [root](/page/Root)
function buildHuffmanTree(symbols, probabilities):
initialize priority queue Q as empty min-heap (keyed by probability)
for i from 1 to n: // n symbols
create leaf node leaf_i with symbol symbols[i] and weight probabilities[i]
insert leaf_i into Q
while size of Q > 1:
node1 = extract-min(Q)
node2 = extract-min(Q)
create internal node [parent](/page/Parent) with weight = node1.weight + node2.weight
set node1 as left [child](/page/Child) of [parent](/page/Parent)
set node2 as right [child](/page/Child) of [parent](/page/Parent)
insert [parent](/page/Parent) into Q
return [root](/page/Root) of Q // the final tree [root](/page/Root)
Encoding Mechanism
Once the Huffman tree has been constructed, the encoding mechanism generates variable-length binary codewords for each symbol by traversing the tree from the root to the corresponding leaf node, assigning a '0' for each left branch and a '1' for each right branch along the path.[1] This traversal process ensures that the resulting codes form a prefix-free set, meaning no codeword is a prefix of another, which allows unambiguous decoding.[23] After building the tree, a code table is precomputed by performing a depth-first traversal to assign and store the binary codewords for all symbols in the alphabet.[23] This table maps each symbol to its unique codeword, facilitating efficient lookup during encoding without repeated tree traversals. To encode a sequence of symbols, the encoder concatenates the codewords from the table for each symbol in the input message, producing a continuous bitstream as output.[1] For example, given symbols A, B, and C with codewords 0, 10, and 11 respectively, the message "ABAC" encodes to the bitstream 010011.[23] This variable-length encoding achieves compression by reducing the average bits per symbol from a fixed-length scheme, such as bits per symbol for an alphabet of size , to shorter codes for frequent symbols and longer ones for rare symbols.[24] The total compressed length of a message with symbols is given by the sum of the lengths of their individual codewords: where is the length of the codeword for symbol .[1] In edge cases, such as an empty message, the encoding produces no bits, though practical implementations may include a special marker like PSEUDO_EOF to signal the end.[23] For a single-symbol alphabet, the Huffman tree consists of a single node serving as both root and leaf, assigning an empty (length-0) codeword to the symbol. In practice, the number of occurrences is encoded separately to allow decoding the correct number of symbols.[25]Decoding Mechanism
The decoding process in Huffman coding reverses the encoding by reconstructing the original sequence of symbols from the compressed bitstream using the pre-built Huffman tree. The decoder begins at the root of the binary tree and reads the incoming bits one at a time. A bit value of 0 directs the traversal to the left child, while 1 directs it to the right child. This continues until a leaf node is reached, at which point the symbol associated with that leaf is output, and the traversal resets to the root for the next symbol. This tree-based approach ensures unambiguous decoding, as the prefix-free property of Huffman codes guarantees that no codeword is a prefix of another, preventing any ambiguity in determining where one symbol's code ends and the next begins.[13] To handle the end of the message, Huffman decoding typically incorporates an explicit sentinel symbol, such as a pseudo-end-of-file (pseudo-EOF) character with frequency 1, which is assigned a codeword during tree construction and appended to the encoded bitstream. The decoder processes bits sequentially until this sentinel code is encountered, signaling the termination of the message; alternatively, in some implementations, decoding continues until the entire bitstream is consumed, assuming the input length is known in advance. If the bitstream ends prematurely without the sentinel, an error is raised. This mechanism avoids the need for additional length indicators while maintaining reliable termination.[26] The following pseudocode illustrates the core decoding loop, assuming a binary tree structure where nodes have left/right children and leaves store symbols:function decode(bitstream, huffman_tree):
root = huffman_tree.root
current = root
output = []
while not bitstream.end_of_stream():
bit = bitstream.read_bit()
if bit == 0:
current = current.left
else:
current = current.right
if current.is_leaf():
symbol = current.symbol
if symbol == PSEUDO_EOF:
break
output.append(symbol)
current = root
return output
function decode(bitstream, huffman_tree):
root = huffman_tree.root
current = root
output = []
while not bitstream.end_of_stream():
bit = bitstream.read_bit()
if bit == 0:
current = current.left
else:
current = current.right
if current.is_leaf():
symbol = current.symbol
if symbol == PSEUDO_EOF:
break
output.append(symbol)
current = root
return output