AlgoTales · Roadmap

Huffman coding

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Huffman coding shrinks data by giving short codes to common symbols and long codes to rare ones. It builds those codes greedily by repeatedly joining the two rarest items, and gives the smallest possible size for this kind of symbol-by-symbol scheme.

Practical use cases

  • Web app: Shrinking a text export for storage. A reporting page lets users download a big log or text file. Letters such as e and space appear far more than z, so giving them shorter codes makes the file about 40 percent smaller, which means faster downloads on a mobile connection.
  • Web app: Gzip on your web server. Your server compresses HTML, CSS and JavaScript before sending it. Huffman coding is one of the building blocks in that process, so the same page loads with fewer bytes and appears faster.
  • Web app: Image and audio downloads. JPEG images and MP3 audio use Huffman-style coding in their final step to squeeze data, which is why a gallery page can load many photos quickly.
  • System: ZIP files and old telegraphs. ZIP uses it in its Deflate method, and the idea of short codes for common letters goes back to Morse code and telegraph messages.

The story: The Telegram With Few Words

Grandpa Bhaskar told Mira about telegram days: every letter you sent cost money. "We always wrote the shortest message we could," he laughed. Then he showed her a trick the telegraph operators loved: the letter used most often should have the shortest code.

Morse code already did it: "E" is a single dot, but "Q" is long. Mira asked, "How do we build the best codes for any message?" Grandpa pulled out a bag of buttons. Each letter was a pile: f had 45 buttons, e had 16, d 13, c 12, b 9, a 5.

"Take the two smallest piles and tie them together into one bigger pile," he said. Mira joined a (5) and b (9) into a pile of 14. Then c and d into 25. Then that 14 with e (16) into 30. She kept going, always tying the two lightest piles, until just one big pile remained at the top: a tree!

Then Grandpa said: "Walk from the top. Go left, write 0. Go right, write 1." The popular f was one step from the top, so its code was a single digit. The rare a and b were deep, so their codes were long. That is Huffman coding, the greedy idea behind ZIP, JPEG and MP3 shrinkers. And no letter's code is the start of another, so there is never any confusion when decoding.

How to spot this problem, and where you need it

You store or send lots of data where some values appear far more often than others, and you want to make it smaller without losing anything.

Signs you need it

  • Frequency counts are very uneven: a few characters, tags or values make up most of the data.
  • Files or API responses are large and bandwidth or storage costs are a concern.
  • The problem says "variable-length codes", "prefix codes" or "minimum total encoded length".

Where to use it in a project

  • Compressing downloads, backups, CSV exports and API responses before they are sent to the browser.
  • Understanding what gzip, ZIP, PNG and JPEG are doing for your site behind the scenes.

The solution

Count how often each symbol appears. Put them in a priority queue by count. Repeatedly remove the two least frequent, join them into a new node whose count is their sum, and put it back. When one node remains you have a tree. Walk from the top: left means 0, right means 1; the path to each symbol is its code. Rare symbols end up deep with long codes and common ones near the top with short codes.

Payoff: Before: a 5 MB text file at 8 bits per letter. After: roughly 3 MB, with every character restored exactly on decoding.

Explain it like I am 8

Give short nicknames to the friends you talk about all the time, and long names only to the ones you rarely mention. To build the nicknames, always join the two least popular friends together first, and repeat until everyone is in one big group.

How it works, step by step

  1. Count how often each symbol appears. Each symbol is a tiny tree of its own.
  2. Take the two trees with the smallest counts and join them under a new parent whose count is their sum.
  3. Put the new tree back with the others and repeat until just one tree remains.
  4. Read the codes: from the top, add 0 for each left turn and 1 for each right turn until you reach a letter.
  5. Frequent letters sit near the top (short codes) and rare ones deep down (long codes).

The code in four languages

PHP

<?php
// freq: letter => how often. Builds Huffman codes the greedy way.
function huffman(array $freq): array {
    $nodes = [];
    $id = 0;
    foreach ($freq as $ch => $w) $nodes[] = ['w' => $w, 'ch' => $ch, 'id' => $id++, 'l' => null, 'r' => null];

    while (count($nodes) > 1) {
        // smallest count first; ties broken by creation order
        usort($nodes, fn($a, $b) => $a['w'] <=> $b['w'] ?: $a['id'] <=> $b['id']);
        $left = array_shift($nodes);                 // two smallest pieces
        $right = array_shift($nodes);
        $nodes[] = ['w' => $left['w'] + $right['w'], 'ch' => null, 'id' => $id++, 'l' => $left, 'r' => $right];
    }

    $codes = [];
    $walk = function (array $n, string $path) use (&$walk, &$codes) {
        if ($n['ch'] !== null) { $codes[$n['ch']] = $path === '' ? '0' : $path; return; }
        $walk($n['l'], $path . '0');                 // left = 0
        $walk($n['r'], $path . '1');                 // right = 1
    };
    $walk($nodes[0], '');
    return $codes;
}

$freq = ['a' => 5, 'b' => 9, 'c' => 12, 'd' => 13, 'e' => 16, 'f' => 45];
$codes = huffman($freq);
$bits = 0;
foreach ($freq as $ch => $w) { echo "$ch = {$codes[$ch]}\n"; $bits += $w * strlen($codes[$ch]); }
echo "Total bits: $bits";                            // 224

JavaScript

// freq: letter => how often. Builds Huffman codes the greedy way.
function huffman(freq) {
  let nodes = [];
  let id = 0;
  for (const ch in freq) nodes.push({ w: freq[ch], ch: ch, id: id++, l: null, r: null });

  while (nodes.length > 1) {
    // smallest count first; ties broken by creation order
    nodes.sort((a, b) => a.w - b.w || a.id - b.id);
    const left = nodes.shift();                    // two smallest pieces
    const right = nodes.shift();
    nodes.push({ w: left.w + right.w, ch: null, id: id++, l: left, r: right });
  }

  const codes = {};
  const walk = (n, path) => {
    if (n.ch !== null) { codes[n.ch] = path === '' ? '0' : path; return; }
    walk(n.l, path + '0');                         // left = 0
    walk(n.r, path + '1');                         // right = 1
  };
  walk(nodes[0], '');
  return codes;
}

const freq = { a: 5, b: 9, c: 12, d: 13, e: 16, f: 45 };
const codes = huffman(freq);
let bits = 0;
for (const ch in freq) { console.log(ch + ' = ' + codes[ch]); bits += freq[ch] * codes[ch].length; }
console.log('Total bits: ' + bits);                 // 224

Java

import java.util.*;

public class Main {
    static class Node {
        int w, id;
        Character ch;          // null for an inner node
        Node l, r;
        Node(int w, Character ch, int id, Node l, Node r) { this.w = w; this.ch = ch; this.id = id; this.l = l; this.r = r; }
    }

    static void walk(Node n, String path, Map<Character, String> codes) {
        if (n.ch != null) { codes.put(n.ch, path.isEmpty() ? "0" : path); return; }
        walk(n.l, path + "0", codes);                  // left = 0
        walk(n.r, path + "1", codes);                  // right = 1
    }

    // freq: letter => how often. Builds Huffman codes the greedy way.
    static Map<Character, String> huffman(Map<Character, Integer> freq) {
        List<Node> nodes = new ArrayList<>();
        int id = 0;
        for (var e : freq.entrySet()) nodes.add(new Node(e.getValue(), e.getKey(), id++, null, null));

        while (nodes.size() > 1) {
            // smallest count first; ties broken by creation order
            nodes.sort(Comparator.comparingInt((Node n) -> n.w).thenComparingInt(n -> n.id));
            Node left = nodes.remove(0);               // two smallest pieces
            Node right = nodes.remove(0);
            nodes.add(new Node(left.w + right.w, null, id++, left, right));
        }

        Map<Character, String> codes = new HashMap<>();
        walk(nodes.get(0), "", codes);
        return codes;
    }

    public static void main(String[] args) {
        Map<Character, Integer> freq = new LinkedHashMap<>();
        freq.put('a', 5); freq.put('b', 9); freq.put('c', 12);
        freq.put('d', 13); freq.put('e', 16); freq.put('f', 45);
        var codes = huffman(freq);
        int bits = 0;
        for (var e : freq.entrySet()) {
            System.out.println(e.getKey() + " = " + codes.get(e.getKey()));
            bits += e.getValue() * codes.get(e.getKey()).length();
        }
        System.out.println("Total bits: " + bits);     // 224
    }
}

Go

package main

import (
	"fmt"
	"sort"
)

type Node struct {
	w, id int
	ch    rune // 0 for an inner node
	l, r  *Node
}

type Letter struct {
	ch rune
	w  int
}

// huffman builds Huffman codes the greedy way, from letters and how often they appear.
func huffman(freq []Letter) map[rune]string {
	var nodes []*Node
	id := 0
	for _, f := range freq {
		nodes = append(nodes, &Node{w: f.w, ch: f.ch, id: id})
		id++
	}

	for len(nodes) > 1 {
		// smallest count first; ties broken by creation order
		sort.Slice(nodes, func(i, j int) bool {
			if nodes[i].w != nodes[j].w {
				return nodes[i].w < nodes[j].w
			}
			return nodes[i].id < nodes[j].id
		})
		left, right := nodes[0], nodes[1] // two smallest pieces
		nodes = nodes[2:]
		nodes = append(nodes, &Node{w: left.w + right.w, id: id, l: left, r: right})
		id++
	}

	codes := map[rune]string{}
	var walk func(n *Node, path string)
	walk = func(n *Node, path string) {
		if n.ch != 0 {
			if path == "" {
				path = "0"
			}
			codes[n.ch] = path
			return
		}
		walk(n.l, path+"0") // left = 0
		walk(n.r, path+"1") // right = 1
	}
	walk(nodes[0], "")
	return codes
}

func main() {
	freq := []Letter{{'a', 5}, {'b', 9}, {'c', 12}, {'d', 13}, {'e', 16}, {'f', 45}}
	codes := huffman(freq)
	bits := 0
	for _, f := range freq {
		fmt.Printf("%c = %s\n", f.ch, codes[f.ch])
		bits += f.w * len(codes[f.ch])
	}
	fmt.Println("Total bits:", bits) // 224
}

Time: O(n log n) · Extra space: O(n). With a priority queue (heap), each of the n-1 joins costs O(log n). The sort-each-time version above is simpler but slower.

Watch out for

  • Joining the two largest pieces instead of the two smallest.
  • Forgetting a one-letter message: its code needs at least one bit, which is why we use "0" there.
  • Mixing up codes: the same left/right rule (0/1) must be used when encoding and decoding.

Quick check

  1. Which two pieces does Huffman join each round?
    • The two largest
    • The two smallest
    • The smallest and the largest
  2. Which letter ends up with the shortest code?
    • The rarest one
    • The first alphabetically
    • The most frequent one
  3. Why can a decoder read the bits without confusion?
    • No code is the beginning of another code
    • Every code has the same length
    • Spaces separate the codes