1. Gyanastra
  2. Algorithms
  3. Huffman Coding and Optimal Merge Pattern
  4. Huffman's Algorithm
Free lesson, no account needed 4 min read
Asked in past papers7 times
  • GATE CSE20172007
  • UGC NET20182017201620152014

Algorithms · Huffman Coding and Optimal Merge Pattern

Huffman's Algorithm

2.1 The greedy step

Repeatedly take the two nodes of smallest weight and merge them into a new node whose weight is their sum. The two removed nodes become its children.

2.2 Step-by-step method (exam recipe)

  1. Create a leaf for each symbol with weight fif_i. Put all leaves in a min-heap keyed by weight.
  2. Repeat n−1n-1 times:
    • Extract-min twice → nodes x,yx,y with weights wx≤wyw_x \le w_y.
    • Create internal node zz with weight wz=wx+wyw_z = w_x + w_y; make xx the left child (edge 0) and yy the right child (edge 1) — the 0/1 assignment is a convention and does not affect cost.
    • Insert zz into the heap.
  3. The single remaining node is the root. Read codewords off the root-to-leaf paths.
  4. Total bits B=∑fidiB=\sum f_i d_i; average length Lˉ=B/N\bar L = B/N.

2.3 Complexity

Each heap operation is O(log⁡n)O(\log n); there are nn insertions and 2(n−1)2(n-1) extract-mins plus n−1n-1 insertions of internal nodes, i.e. O(n)O(n) heap operations. Total:

T(n)=O(nlog⁡n)T(n)=O(n\log n)

If the frequencies are already sorted, a two-queue method (one queue of leaves, one queue of merged nodes, both sorted) gives O(n)O(n) — a fact GATE has asked about.

2.4 Structural facts

  • A full binary tree with nn leaves has exactly n−1n-1 internal nodes and 2n−12n-1 nodes total.
  • Hence the Huffman tree for nn symbols has n−1n-1 merges and n−1n-1 internal nodes.
  • No leaf has depth 0 unless n=1n=1 (degenerate case).
  • Some optimal tree has the two least frequent symbols as siblings at maximum depth (this is the exchange argument behind optimality; with ties not every optimal tree has this shape).

2.5 Why it is optimal (exchange argument, sketch)

Take any optimal tree TT. Let a,ba,b be the two least frequent symbols. One can swap them with the two deepest sibling leaves without increasing cost (because exchanging a lighter symbol with a heavier, shallower one never increases ∑fidi\sum f_i d_i: the change is (fa−fx)(dx−da)≤0(f_a-f_x)(d_x-d_a)\le 0). So some optimal tree has a,ba,b as deepest siblings. Contracting them into one leaf of weight fa+fbf_a+f_b reduces the problem to n−1n-1 symbols, and the cost of the original tree equals the cost of the contracted tree plus fa+fbf_a+f_b. By induction the greedy choice is safe — the greedy-choice and optimal-substructure properties hold, so Huffman is optimal among all prefix codes.


Pages 1–2 of 2