Algorithms · Visualized

Compression: Huffman

Compression & Encoding

Shrink data with runs, frequencies, and clever codes.

A compression technique that assigns shorter binary codes to more frequent characters and longer codes to rarer ones, minimizing the total encoded size. Time: O(n log n) average, O(n log n), where n is the number of distinct characters worst; space: O(n) — the Huffman tree and code table.

Big-O: Huffman gives prefix-free optimal codes.

Huffman Coding

Compression / Encoding

A compression technique that assigns shorter binary codes to more frequent characters and longer codes to rarer ones, minimizing the total encoded size. It builds an optimal 'prefix code' tree by repeatedly combining the two least-frequent nodes into a new parent node, using a min-heap, until only one tree remains.

How Huffman Works

  1. Count the frequency of every character in the input.
  2. Create a leaf node for each character with its frequency, and add all leaves to a min-heap (priority queue) ordered by frequency.
  3. Repeatedly remove the two nodes with the smallest frequencies from the heap, create a new internal node with these two as children and a frequency equal to their sum, and insert this new node back into the heap.
  4. Continue merging until only one node remains in the heap — this is the root of the Huffman tree.
  5. Assign codes by traversing the tree from the root: each left branch adds a '0' and each right branch adds a '1' to the code, and each leaf's accumulated path is that character's Huffman code.

Huffman Worked Example

Input: {text: aaabbc, frequencies: {a: 3, b: 2, c: 1}}

Min-heap starts with leaves a(3), b(2), c(1). Merge smallest two: c(1)+b(2)=new node(3). Heap now has a(3) and merged-node(3). Merge these: total root(6). Tree: root→left=a (code '0'), root→right=merged-node→left=b(code '10'), right=c(code '11'). Encoded 'aaabbc' becomes '0 0 0 10 10 11' — shorter overall than fixed-length encoding since 'a' (most frequent) gets the shortest code.

Compression: HuffmanO(n log n)
Build optimal prefix-free codes by merging smallest frequencies.
charfreqcode
aa3
bb2
cc1
Step 1 / 4
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Huffman Coding: merge the two smallest-frequency nodes repeatedly; branches become 0/1.
Python · Compression Algorithms in Code
import heapq
from collections import Counter

def huffman_codes(text):
    heap = [[freq, char] for char, freq in Counter(text).items()]
    heapq.heapify(heap)
    while len(heap) > 1:
        left = heapq.heappop(heap)
        right = heapq.heappop(heap)
        heapq.heappush(heap, [left[0] + right[0], left, right])
    codes = {}

    def walk(node, prefix):
        if len(node) == 2:
            codes[node[1]] = prefix or '0'
            return
        walk(node[1], prefix + '0')
        walk(node[2], prefix + '1')

    if heap:
        walk(heap[0], '')
    return codes

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Huffman Time & Space Complexity

BestO(n log n)
AverageO(n log n)
WorstO(n log n), where n is the number of distinct characters
SpaceO(n) — the Huffman tree and code table

When to Use Huffman

  • Widely used in real compression formats: ZIP, JPEG, MP3, and PDF all use Huffman coding (often combined with other techniques) as part of their compression pipeline.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.