Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Text compression: Huffman and arithmetic coding

Huffman coding builds an optimal prefix code from symbol probabilities by a greedy tree algorithm; arithmetic coding represents an entire message as a fractional interval in [0,1) and approaches entropy more tightly.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Two common lossless text-compression techniques used in information retrieval systems are Huffman coding and arithmetic coding. An engineer uses Huffman when they need a simple, fast, symbol-by-symbol prefix code (eg. compress postings lists, metadata); they use arithmetic coding when they need higher compression close to the entropy limit (eg. compressing long sequences or language models). Both reduce storage and I/O cost for indexes and postings (see "Compressing postings lists" elsewhere in the course list).

Key ideas

  • Probability distribution: each symbol s has probability p(s), with p(s) ≥ 0 and sum_s p(s) = 1.

  • Codeword: a finite sequence of bits assigned to a symbol.

  • Prefix code: a set of binary codewords where no codeword is a prefix of another. This guarantees instantaneous decoding (you can decode as you read bits).

  • Average code length: L = Σ_s p(s) · l(s), where l(s) is the length in bits of the codeword for symbol s.

  • Entropy: H = −Σ_s p(s) log_2 p(s). Entropy is a lower bound (in bits per symbol) on the expected code length L for any uniquely decodable code under distribution p; for memoryless sources it is the per-symbol bound, and for dependent sources the entropy rate provides the bound.

  • Redundancy: R = L − H, the extra bits per symbol above entropy.

  • Kraft inequality: a necessary and sufficient condition for existence of a binary prefix code with lengths {l_i} is Σ_i 2^{−l_i} ≤ 1.

  • Huffman code: a prefix code constructed by the Huffman greedy algorithm; it is optimal among prefix codes for a given set of symbol probabilities and integer lengths.

  • Arithmetic coding: encodes an entire sequence as a single fractional number in [0,1) by subdividing intervals proportional to symbol probabilities; it can achieve average bits per symbol arbitrarily close to entropy for long sequences.

  • Important theorems and exact statements (assumptions noted):

    1. (Kraft inequality) For any prefix code with codeword lengths l_1, ..., l_n (integers ≥ 1): Σ_{i=1..n} 2^{−l_i} ≤ 1. Conversely, for any set of positive integers satisfying the inequality there exists a prefix code with those lengths. (Assumes binary alphabet for codewords.) More generally, the same inequality is necessary for any uniquely decodable code (Kraft–McMillan).

      • Proof sketch: think of the full binary tree of infinite depth. Each codeword corresponds to a leaf node at depth l_i. The fraction of leaves it occupies is 2^{−l_i}. Distinct leaves are disjoint, so sum ≤ 1. Construction uses available leaf slots.
    2. (Huffman optimality) Given symbol probabilities and the restriction to prefix codes with integer lengths, the Huffman algorithm produces a prefix code whose average length L is minimal. (Assumes all symbol probabilities > 0; ties in probabilities can lead to multiple optimal trees.)

      • Proof sketch (standard greedy proof): show optimal substructure and greedy choice. Combine two least-probable symbols x,y into a single compound symbol with probability p(x)+p(y). Any optimal tree can be transformed so that x and y are sibling leaves of maximum depth; reducing the problem yields optimality by induction.
    3. (Shannon bounds for prefix codes) For any distribution there exists a prefix code with integer lengths l(s) satisfying l(s) ≤ ⌈−log_2 p(s)⌉. Hence the average length satisfies H ≤ L < H + 1. (The lower bound L ≥ H holds for any uniquely decodable code; the upper bound uses prefix codes and integer rounding.) For Huffman codes, a tighter bound holds: L_Huffman ≤ H + p_max, where p_max = max_s p(s).

      • This shows you cannot do better than H bits/symbol on average, and integer-length prefix codes can get within one bit of H.
  • How to draw the Huffman diagram (for an exam):

    • Start by listing symbols and probabilities. Repeatedly: combine the two smallest probabilities into a single node with probability sum. Draw these as leaf nodes merging into a parent. Continue until there is one root. Label left and right child edges with bits (0 and 1) consistently. The codeword for a symbol is the sequence of bits from root to its leaf. In an answer diagram, annotate each merge with the two probabilities being combined and the resulting sum.
  • Arithmetic coding mechanism (step-by-step idea):

    1. Fix an ordering of symbols and cumulative probabilities: define cumulative intervals [C_{i}, C_{i+1}) for symbol i so that length is p(i).
    2. Start with interval [low, high) = [0,1).
    3. For each symbol s in the message: set range = high − low; update high = low + range · C_{s+1}; low = low + range · C_{s}.
    4. After all symbols, any number x ∈ [low,high) encodes the message uniquely; emit a binary representation of any x inside the interval. Decoding reverses the process: map the code fraction into cumulative ranges to reconstruct symbols.
    • Use half-open intervals [low, high) to avoid endpoint ambiguity.
    • In practice implementations must rescale and emit bits while maintaining finite precision (see common pitfalls).

Formulas

H = -Σ_s p(s) log_2 p(s) — H is entropy (bits/symbol). p(s) is probability of symbol s (dimensionless). Applies to memoryless sources.

L = Σ_s p(s) · l(s) — expected code length in bits per symbol. l(s) is integer codeword length (bits).

Σ_s 2^{-l(s)} ≤ 1 — Kraft inequality for binary prefix codes. l(s) are integers (bits).

H ≤ L < H + 1 — achievable bounds for prefix codes (Shannon coding / integer-length code bound). H and L in bits/symbol.

Redundancy R = L - H — extra bits per symbol compared to entropy.

(For arithmetic coding the updating step as code-like formula)

range <- high - low

high <- low + range * C_{s+1}

low <- low + range * C_{s}

where C_s are cumulative probabilities with C_1 = 0 and C_{n+1} = 1.

Worked examples

  1. Huffman coding (numerical, exam standard)
  • Given symbols and probabilities: A:0.45, B:0.13, C:0.12, D:0.16, E:0.14. Build Huffman tree and find codewords, L and H.
  • Steps:
    1. List probabilities: 0.45(A), 0.16(D), 0.14(E), 0.13(B), 0.12(C).
    2. Combine two smallest: 0.12(C) + 0.13(B) = 0.25 => node (CB).
    3. New list: 0.45(A), 0.16(D), 0.14(E), 0.25(CB).
    4. Combine 0.14(E) + 0.16(D) = 0.30 => node (ED).
    5. New list: 0.45(A), 0.25(CB), 0.30(ED).
    6. Combine 0.25 + 0.30 = 0.55 => node ((CB)(ED)).
    7. Combine 0.45 + 0.55 to form root.
    8. Assign bits: root → left child 0 (A), right child 1 (combined). For right child, assign its left child 0 and right child 1, etc. One consistent assignment yields:
      • A: 0 (length 1)
      • B: 101 (length 3)
      • C: 100 (length 3)
      • D: 111 (length 3)
      • E: 110 (length 3)
  • Compute average length: L = 0.45*1 + 0.13*3 + 0.12*3 + 0.16*3 + 0.14*3 = 2.10 bits/symbol.
  • Compute entropy (use log base 2): H = -(0.45*log2 0.45 + 0.13*log2 0.13 + 0.12*log2 0.12 + 0.16*log2 0.16 + 0.14*log2 0.14) ≈ 2.088 bits/symbol.
  • Redundancy: R = L - H ≈ 0.012 bits/symbol. Final answers: L = 2.10 bits/symbol, H ≈ 2.088 bits/symbol, redundancy ≈ 0.012 bits/symbol.
  1. Arithmetic coding (short sequence)
  • Alphabet: A (0.5), B (0.3), C (0.2). Encode message "BA".
  • Steps:
    1. Cumulative intervals: A: [0.0,0.5), B: [0.5,0.8), C: [0.8,1.0).
    2. Start [low,high) = [0,1).
    3. Symbol 1 = B → range = 1.0; new low = 0 + 1.00.5 = 0.5; new high = 0 + 1.00.8 = 0.8. Interval now [0.5,0.8).
    4. Symbol 2 = A → range = 0.3; A occupies first half of this: new low = 0.5 + 0.30.0 = 0.5; new high = 0.5 + 0.30.5 = 0.65. Final interval [0.5,0.65).
    5. Choose any number inside, e.g. 0.55. Find shortest binary fraction whose whole binary-interval is contained in [0.5,0.65). Check prefixes:
      • 1-bit prefix '1' => interval [0.5,1.0) not contained (too wide).
      • 2-bit prefix '10' => [0.5,0.75) not contained (upper > 0.65).
      • 3-bit prefix '100' => [0.5,0.625) is contained inside [0.5,0.65).
    6. So encoded bitstring = 100 (3 bits). Final answer: encoded bits = 100.

Common mistakes

  • Mixing up average length L and entropy H; failing to compute H with log base 2.
  • In arithmetic coding examples: not using half-open intervals [low,high) (endpoint ambiguity), or choosing a binary fraction whose interval is not fully inside the final interval (makes decoding ambiguous).
  • Ignoring finite-precision issues in arithmetic coding (practical encoders use rescaling/bit-output during encoding; naive infinite-precision arithmetic is not implementable).
  • Errors in tree-building: when combining equal-probability nodes ties can produce different but equally optimal codes — always explain tie-breaking if asked.

For your exam

  • Short notes: describe Huffman algorithm, arithmetic coding and practical issues (rescaling, adaptive coding).
  • Derivations/proofs: prove Kraft inequality; prove greedy optimality of Huffman (outline acceptable if time-limited); derive H ≤ L < H + 1.
  • Numerical: build a Huffman tree for given probabilities and compute L and compare with H; perform a short arithmetic coding encoding/decoding.
  • Diagrams: draw Huffman tree with probabilities and merged nodes.
  • What full-marks answers include:
    • Clear definitions (bold the term if asked), assumptions stated (memoryless source, independent symbols), step-by-step algorithm, and final computed numerical answers with units (bits/symbol) and brief interpretation (redundancy, closeness to entropy). For proofs, include the base case and inductive or greedy argument, and state where tie cases do not affect optimality.

Quick check

  1. State the Kraft inequality for binary prefix codes.
  2. Give one sentence that distinguishes Huffman coding from arithmetic coding.
  3. If a symbol has probability 1/8, what is the minimum integer code length suggested by −log2 p? Answers: 1) Σ_i 2^{-l_i} ≤ 1. 2) Huffman assigns fixed integer-length codewords per symbol using a tree (symbol-by-symbol); arithmetic coding encodes a whole sequence as a fraction in [0,1) and can approach entropy more closely for sequences. 3) −log2(1/8) = 3, so minimum integer length is 3.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?