Huffman Coding
Text is normally stored with a fixed-length code: in ASCII every character takes 8 bits, whether it is a common e or a rare z. Huffman coding (David Huffman, 1952) assigns shorter codes to frequent characters and longer codes to rare ones, so the total number of bits shrinks. It is a lossless compression method used inside ZIP (deflate), PNG, JPEG and MP3.
Prefix codes
Variable-length codes have a danger: if a = 0 and b = 01, does 01 mean "a then something" or "b"? Huffman codes are prefix codes: no code is the beginning of another one, so a bit stream can be decoded unambiguously from left to right. Such codes correspond to paths in a binary tree: 0 = go left, 1 = go right, and every character sits at a leaf.
The algorithm
Huffman's algorithm is greedy:
- Count how often each character occurs. Make a one-node tree for each character, weighted by its count.
- Repeatedly take the two trees with the smallest weights and join them under a new parent whose weight is their sum.
- When one tree is left, read each character's code from the path to its leaf.
Rare characters are merged early and end up deep in the tree (long codes); frequent ones are merged late and stay near the root (short codes).
Implementation
A min-heap (heapq) gives the two lightest trees quickly. A counter breaks ties between equal weights so the result is deterministic.
import heapq
from collections import Counter
def huffman_codes(text):
counts = Counter(text)
heap = []
for order, (ch, n) in enumerate(sorted(counts.items())):
heap.append((n, order, ch)) # a leaf is just the character
heapq.heapify(heap)
order = len(heap)
while len(heap) > 1:
w1, _, left = heapq.heappop(heap)
w2, _, right = heapq.heappop(heap)
print(f"merge {left!r} ({w1}) + {right!r} ({w2}) -> {w1 + w2}")
heapq.heappush(heap, (w1 + w2, order, (left, right)))
order += 1
codes = {}
def walk(node, path):
if isinstance(node, str):
codes[node] = path or "0"
return
walk(node[0], path + "0")
walk(node[1], path + "1")
walk(heap[0][2], "")
return counts, codes
text = "abracadabra"
counts, codes = huffman_codes(text)
for ch in sorted(codes, key=lambda c: (len(codes[c]), c)):
print(f"{ch!r}: count {counts[ch]}, code {codes[ch]}")merge 'c' (1) + 'd' (1) -> 2
merge 'b' (2) + 'r' (2) -> 4
merge ('c', 'd') (2) + ('b', 'r') (4) -> 6
merge 'a' (5) + (('c', 'd'), ('b', 'r')) (6) -> 11
'a': count 5, code 0
'b': count 2, code 110
'c': count 1, code 100
'd': count 1, code 101
'r': count 2, code 111
a occurs 5 times and gets a 1-bit code; all the other characters get 3 bits. The rare c and d were merged first, deep in the tree.
Encoding and decoding
codes = {"a": "0", "b": "110", "c": "100", "d": "101", "r": "111"} # from above
text = "abracadabra"
bits = "".join(codes[ch] for ch in text)
print(bits)
print(f"{len(bits)} bits instead of {8 * len(text)} (ASCII) or {3 * len(text)} (3-bit fixed code)")
# decoding: read bits until they match a code (works because it's a prefix code)
reverse = {code: ch for ch, code in codes.items()}
out, current = [], ""
for bit in bits:
current += bit
if current in reverse:
out.append(reverse[current])
current = ""
print("".join(out))01101110100010101101110
23 bits instead of 88 (ASCII) or 33 (3-bit fixed code)
abracadabra
23 bits instead of 88. Even compared with the best fixed-length code for 5 symbols (3 bits each, 33 bits), Huffman saves 30%.
Is it optimal?
Huffman coding is optimal among prefix codes that encode one character at a time: no other such code produces fewer bits for the given frequencies. Let's compare the average bits per character with the theoretical limit, the entropy of the character distribution:
import heapq, math
from collections import Counter
def code_lengths(text):
counts = Counter(text)
heap = [(n, i, [ch]) for i, (ch, n) in enumerate(sorted(counts.items()))]
heapq.heapify(heap)
depth = {ch: 0 for ch in counts}
i = len(heap)
while len(heap) > 1:
w1, _, a = heapq.heappop(heap)
w2, _, b = heapq.heappop(heap)
for ch in a + b:
depth[ch] += 1 # every merge adds one bit to its leaves
heapq.heappush(heap, (w1 + w2, i, a + b))
i += 1
return counts, depth
text = "she sells sea shells by the sea shore"
counts, depth = code_lengths(text)
n = len(text)
avg = sum(counts[c] * depth[c] for c in counts) / n
entropy = -sum(counts[c] / n * math.log2(counts[c] / n) for c in counts)
print(f"{len(counts)} distinct characters, {n} in total")
print(f"Huffman: {sum(counts[c] * depth[c] for c in counts)} bits, {avg:.3f} bits/char")
print(f"entropy: {entropy:.3f} bits/char (lower bound)")
print(f"fixed-length: {math.ceil(math.log2(len(counts)))} bits/char")11 distinct characters, 37 in total
Huffman: 114 bits, 3.081 bits/char
entropy: 3.012 bits/char (lower bound)
fixed-length: 4 bits/char
Huffman's average is within one bit of the entropy limit (here much closer). Methods like arithmetic coding get even closer by not assigning a whole number of bits to each character.
Practical notes
- The decoder needs the code table (or the frequencies), so it is stored with the compressed data. For short texts this overhead can outweigh the savings.
- Huffman works on any symbols: bytes, pixel values, or the match lengths produced by LZ77 in deflate.
- The time to build the tree is
O(k log k)forkdistinct symbols, using a heap.
Test yourself
Which characters get the shortest Huffman codes?
- The rarest
- The most frequent
- Vowels
- Characters early in the alphabet
What is a prefix code?
- A code where all codes have the same length
- A code where no code is the beginning of another
- A code that starts with 0
- A code stored before the data
At each step, which trees does Huffman's algorithm merge?
- The two heaviest
- The two with the smallest weights
- The first two in alphabetical order
- Any two