1. Gyanastra
  2. Algorithms
  3. Huffman Coding and Optimal Merge Pattern
  4. The Problem Being Solved
Free lesson, no account needed 4 min read
Asked in past papers1 time
  • GATE CSE1991

Algorithms · Huffman Coding and Optimal Merge Pattern

The Problem Being Solved

Suppose a file contains nn distinct symbols. Symbol ii occurs fif_i times, so the file has N=∑i=1nfiN=\sum_{i=1}^{n} f_i characters. We want to assign each symbol a binary codeword so that the file can be stored (or transmitted) in as few bits as possible, and so that the encoded stream can be decoded unambiguously.

Two ideas combine:

  1. Variable-length codes — give short codewords to frequent symbols, long codewords to rare ones.
  2. The prefix property — no codeword is a prefix of another codeword. This makes decoding possible without any separator characters.

Huffman's algorithm (David Huffman, 1952) builds the optimal prefix code for a given frequency distribution.

1.1 Fixed-length vs variable-length

With nn symbols, a fixed-length code needs ⌈log⁡2n⌉\lceil \log_2 n \rceil bits per symbol. For n=6n=6 that is ⌈2.585⌉=3\lceil 2.585 \rceil = 3 bits per symbol, regardless of frequencies. A variable-length code can do better whenever the distribution is skewed.

1.2 The prefix property (definition)

A code is a prefix code (prefix-free code) if no codeword is a proper prefix of any other codeword.

  • Valid: {0, 10, 11}\{0,\ 10,\ 11\} — no codeword starts another.
  • Invalid: {0, 01, 1}\{0,\ 01,\ 1\} — 00 is a prefix of 0101, so the stream 0101 could be read as "00 then 11" or as "0101".

Key theorem (stated, not proved here): every prefix code corresponds to a binary tree whose leaves are the symbols, with left edge = 0 and right edge = 1; the codeword is the root-to-leaf path. Conversely every binary tree with nn leaves gives a prefix code. So designing an optimal prefix code = designing an optimal binary tree.

1.3 Cost formulas

Let did_i = depth of leaf ii = length of codeword ii.

QuantityFormulaMeaning
Total encoded bitsB=∑i=1nfi diB=\sum_{i=1}^{n} f_i\, d_isize of the compressed file
Average bits per symbolLˉ=BN=∑i=1npidi\bar L = \dfrac{B}{N}=\sum_{i=1}^{n} p_i d_i, with pi=fi/Np_i=f_i/Nweighted path length
Entropy (lower bound)H=−∑pilog⁡2piH=-\sum p_i \log_2 p_iH≤Lˉ<H+1H \le \bar L < H+1 for Huffman codes

The quantity ∑fidi\sum f_i d_i is also called the weighted external path length of the tree. Minimising it is exactly the goal.


Pages 1–2 of 2