Huffman Coding

Huffman coding is the optimal scheme for encoding a discrete random variable using prefix free codewords, such that no codeword is a prefix of another codeword.

It constructs a binary tree, where the leaves correspond to symbols, by greedily combining the lowest probability nodes first and building the tree in a bottom-up fashion. This ensures that higher probability symbols are assigned shorter codewords, while lower probability symbols receive longer codewords:

\usepackage{tikz}
 
\begin{document}
 
\begin{tikzpicture}[ 
 level distance=1.5cm,
 level 1/.style={sibling distance=3cm},
 level 2/.style={sibling distance=3cm},
 level 3/.style={sibling distance=3cm},
 scale=0.75
]
 
% Root node
\node {} 
   child { node {\( p_1 \)} 
       edge from parent node[above left] {0} }
   child { node {} 
       child { node {\( p_2 \)} 
           edge from parent node[above left] {0} }
       child { node {  } 
          child { node {}
              child { node {\( p_{n-1} \)} 
                  edge from parent node[above left] {0} }
              child { node {\( p_{n} \)} 
                  edge from parent node[above right] {1} }
              edge from parent[draw=none] node[midway] {\( \vdots \)}
          }
          edge from parent node[above right] {1}
       }
       edge from parent node[above right] {1}
   };
 
\end{tikzpicture}
 
\end{document}

Huffman coding achieves an expected codeword length that is always at least the entropy and at most , ensuring near-optimal compression while maintaining a prefix-free structure.

Examples

Four Symbols

Consider the alphabet , where each symbol occurs at probabilities . Then,

  • The naive coding approach leaves our expected length at bits per symbol (i.e. ).
  • The Huffman codewords are (note that they are prefix free). Given the probabilities of each symbol, as well as their codeword lengths, is bits per symbol.

However, the Shannon Entropy is , where . Therefore, by Shannon’s source coding theorem, there are more efficient source coding algorithms than Huffman code.