ArticleslgStudy

computer science

Huffman coding

Huffman coding is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Huffman coding rather than just read about it. In short: 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 coding — main illustration
Huffman coding — illustration

Key takeaways

  • Huffman coding belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Huffman coding to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Huffman coding from memory before moving on to harder problems.

Reference excerpt

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". 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. However, although optimal among methods encoding symbols separately, Huffman coding is not always optimal among all compression methods – it is replaced with arithmetic coding if a better compression ratio is required.

History 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. 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 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

Informal description Given A set of symbols S {\displaystyle S} and for each symbol x ∈ S {\displaystyle x\in S} , the frequency f x {\displaystyle f_{x}} representing the fraction of symbols in the text that are equal to x {\displaystyle x} . 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 Input. Alphabet A = ( a 1 , a 2 , … , a n ) {\displaystyle A=(a_{1},a_{2},\dots ,a_{n})} , which is the symbol alphabet of size n {\displaystyle n} . Tuple W = ( w 1 , w 2 , … , w n ) {\displaystyle W=(w_{1},w_{2},\dots ,w_{n})} , which is the tuple of the (positive) symbol weights (usually proportional to probabilities), i.e. w i = weight ⁡ ( a i ) , i ∈ { 1 , 2 , … , n } {\displaystyle w_{i}=\operatorname {weight} \left(a_{i}\right),\,i\in \{1,2,\dots ,n\}} .

Output. Code C ( W ) = ( c 1 , c 2 , … , c n ) {\displaystyle C\left(W\right)=(c_{1},c_{2},\dots ,c_{n})} , which is the tuple of (binary) codewords, where c i {\displaystyle c_{i}} is the codeword for a i , i ∈ { 1 , 2 , … , n } {\displaystyle a_{i},\,i\in \{1,2,\dots ,n\}} .

Goal. Let L ( C ( W ) ) = ∑ i = 1 n w i length ⁡ ( c i ) {\textstyle L(C(W))=\sum _{i=1}^{n}w_{i}\operatorname {length} (c_{i})} be the weighted path length of code C {\displaystyle C} . Condition: L ( C ( W ) ) ≤ L ( T ( W ) ) {\displaystyle L(C(W))\leq L(T(W))} for any code T ( W ) {\displaystyle T(W)} .

… excerpt ends here. Continue reading the full article.

Illustrations

Huffman coding: Huffman tree generated from the exact frequencies of the text "this is an example of a huffman tree". Encoding the sentence with this code requires 135 (or 147) bits, as opposed to 288 (or 180) bits if 36 characters of 8 (or 5) bits were used (This assumes that the code tree structure is known to the decoder and thus does not need to be counted as part of the transmitted information). The frequencies and codes of each character are shown in the accompanying table.


CharFreqCode

space7111

a4010

e4000

f31101

h21010

i21000

m20111

n20010

s21011

t20110

l111001

o100110

p110011

r111000

u100111

x110010
Huffman tree generated from the exact frequencies of the text "this is an example of a huffman tree". Encoding the sentence with this code requires 135 (or 147) bits, as opposed to 288 (or 180) bits if 36 characters of 8 (or 5) bits were used (This assumes that the code tree structure is known to the decoder and thus does not need to be counted as part of the transmitted information). The frequencies and codes of each character are shown in the accompanying table. CharFreqCode space7111 a4010 e4000 f31101 h21010 i21000 m20111 n20010 s21011 t20110 l111001 o100110 p110011 r111000 u100111 x110010
Huffman coding: Constructing a Huffman tree
Constructing a Huffman tree
Huffman coding: Visualisation of the use of Huffman coding to encode the message "A_DEAD_DAD_CEDED_A_BAD_BABE_A_BEADED_ABACA_BED". In steps 2 to 6, the letters are sorted by increasing frequency, and the least frequent two at each step are combined and reinserted into the list, and a partial tree is constructed. The final tree in step 6 is traversed to generate the dictionary in step 7. Step 8 uses it to encode the message.
Visualisation of the use of Huffman coding to encode the message "A_DEAD_DAD_CEDED_A_BAD_BABE_A_BEADED_ABACA_BED". In steps 2 to 6, the letters are sorted by increasing frequency, and the least frequent two at each step are combined and reinserted into the list, and a partial tree is constructed. The final tree in step 6 is traversed to generate the dictionary in step 7. Step 8 uses it to encode the message.
Huffman coding: A source generates 4 different symbols 
  
    
      
        {
        
          a
          
            1
          
        
        ,
        
          a
          
            2
          
        
        ,
        
          a
          
            3
          
        
        ,
        
          a
          
            4
          
        
        }
      
    
    {\displaystyle \{a_{1},a_{2},a_{3},a_{4}\}}
  
 with probability 
  
    
      
        {
        0.4
        ;
        0.35
        ;
        0.2
        ;
        0.05
        }
      
    
    {\displaystyle \{0.4;0.35;0.2;0.05\}}
  
. A binary tree is generated from left to right taking the two least probable symbols and putting them together to form another equivalent symbol having a probability that equals the sum of the two symbols. The process is repeated until there is just one symbol. The tree can then be read backwards, from right to left, assigning different bits to different branches. The final Huffman code is:

SymbolCode

a10

a210

a3110

a4111


The standard way to represent a signal made of 4 symbols is by using 2 bits/symbol, but the entropy of the source is 1.74 bits/symbol. If this Huffman code is used to represent the signal, then the average length is lowered to 1.85 bits/symbol; it is still far from the theoretical limit because the probabilities of the symbols are different from negative powers of two.
A source generates 4 different symbols { a 1 , a 2 , a 3 , a 4 } {\displaystyle \{a_{1},a_{2},a_{3},a_{4}\}} with probability { 0.4 ; 0.35 ; 0.2 ; 0.05 } {\displaystyle \{0.4;0.35;0.2;0.05\}} . A binary tree is generated from left to right taking the two least probable symbols and putting them together to form another equivalent symbol having a probability that equals the sum of the two symbols. The process is repeated until there is just one symbol. The tree can then be read backwards, from right to left, assigning different bits to different branches. The final Huffman code is: SymbolCode a10 a210 a3110 a4111 The standard way to represent a signal made of 4 symbols is by using 2 bits/symbol, but the entropy of the source is 1.74 bits/symbol. If this Huffman code is used to represent the signal, then the average length is lowered to 1.85 bits/symbol; it is still far from the theoretical limit because the probabilities of the symbols are different from negative powers of two.

Worked examples

Example 1 — a first encounter with Huffman coding

Start with the simplest possible case. Write down what Huffman coding claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Huffman coding before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Huffman coding ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Huffman coding

In research
Huffman coding appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Huffman coding in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Huffman coding is common in secondary-school and first-year university syllabi. It links to neighbouring topics 1952 in computing, Binary trees, Data compression, so understanding it makes those chapters shorter.
In everyday life
Look for Huffman coding outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Huffman coding” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Huffman coding in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Huffman coding means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Huffman coding out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Huffman coding in simple terms?

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.

Why does Huffman coding matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Huffman coding?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Huffman coding.

Tags

  • 1952 in computing
  • Binary trees
  • Data compression
  • Lossless compression algorithms

Keep exploring