Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 52 / 66

Short codes for frequent symbols.

Build a prefix-free variable-length code with repeated minimum-weight merges.

BY NAVAN SAMI◷ 11 MIN READSTRETCHALGORITHM

01 Model the idea

Huffman coding builds an optimal binary prefix code for a fixed known set of symbol frequencies under its coding model. Repeatedly merge the two lightest subtrees, then assign bit labels along root-to-leaf paths. Frequent symbols tend to receive shorter codes. A prefix code can be decoded without separators because no complete symbol code is a prefix of another.

THE THING THAT MUST STAY TRUE

Each merged subtree’s weight equals the frequencies of all leaves beneath it.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
MERGE the two lightest subtrees repeatedly
LABEL left/right edges with bits
READ each symbol’s root-to-leaf code

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

huffman.py
import heapq
from itertools import count
def huffman(frequencies):
    serial = count()
    heap = [(weight, next(serial), symbol) for symbol, weight in frequencies.items()]
    if not heap: return {}
    if any(type(weight) is not int or weight <= 0 for weight in frequencies.values()):
        raise ValueError("Positive integer frequencies required")
    heapq.heapify(heap)
    while len(heap) > 1:
        a, _, left = heapq.heappop(heap)
        b, _, right = heapq.heappop(heap)
        heapq.heappush(heap, (a + b, next(serial), (left, right)))
    codes = {}
    def walk(node, prefix):
        if isinstance(node, str): codes[node] = prefix or "0"
        else: walk(node[0], prefix + "0"); walk(node[1], prefix + "1")
    walk(heap[0][2], "")
    return codes
codes = huffman({"A": 5, "B": 2, "C": 1})
print(sorted(codes.items()))
↳ EXPECTED OUTPUT
[('A', '1'), ('B', '01'), ('C', '00')]
  1. 1

    The monotonic counter avoids comparing unlike subtree objects when weights tie. Tie choices may produce different equally optimal code assignments.

  2. 2

    The single-symbol convention uses 0 instead of an empty code, making repeated-symbol representation easier to demonstrate. A real format must also define how symbol count and the codebook are stored.

  3. 3

    The heap merging takes O(σ log σ) for σ symbols. Constructing explicit bit strings also costs the total code length L; skewed trees can produce quadratic total codebook length.

04 Count the cost

TIME

O(σ log σ + L) including explicit codebook strings

SPACE

O(σ + L) plus tree recursion depth

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Check that no generated code is a prefix of another code in the fixture.

Reveal one possible solution +
one_possible_solution.py
codes = {"A": "1", "B": "01", "C": "00"}
assert all(not second.startswith(first) for a, first in codes.items() for b, second in codes.items() if a != b)
print("Prefix-free codebook verified")

06 Check your reasoning

QUICK SIGNAL CHECK

Why merge the two least frequent subtrees?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.