Huffman Coding

Pattern: Huffman-style merges

medium

Huffman's method builds the best prefix code by repeatedly joining the two least frequent symbols into one node. The total number of bits needed, the sum of frequency times code length, equals the total cost of those joins, so a min heap gives it directly.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given how often each symbol appears, return the fewest bits needed to write the whole message with a prefix code (no code is the start of another). With frequencies [5, 9, 12, 13, 16, 45] the answer is 224. With only one symbol this count gives 0.

The GFG version asks for the codes themselves, which depend on tie rules; this guide asks for the total, which every correct Huffman tree shares. The catalogue has no practice link for this one.

Think first

  • How does a prefix code look as a tree?
  • What does a symbol's code length equal in that tree?
  • Which two symbols should be siblings at the bottom?

Hints

    Brute force, and why it fails

    Try every tree shape: exponential.

    The key insight

    The total bits is the sum of each frequency times its depth, which equals the sum of all join costs, and joining the two smallest each time makes that sum smallest.

    Dry run

    heap12 13 14 16 45
    bits14

    Frequencies [5, 9, 12, 13, 16, 45]. Join 5 and 9: 14.

    Step 1 of 4

    The plan

    heap = frequencies
    while size > 1: a = pop; b = pop; bits += a + b; push a + b
    return bits
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    n - 1 joins, each a few heap operations.

    Edge cases

    • One symbol: 0 by this count.
    • Two symbols: their sum.
    • Equal frequencies.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public long huffmanBits(int[] freq) {
            PriorityQueue<Long> heap = new PriorityQueue<>();
            for (int x : freq) heap.add((long) x);
            long cost = 0;
            while (heap.size() > 1) {
                long a = heap.poll(), b = heap.poll();  // the two smallest
                cost += a + b;                          // joining them costs their sum
                heap.add(a + b);                        // and the result joins the pile
            }
            return cost;
        }
    }

    C++

    class Solution {
    public:
        long long huffmanBits(vector<int>& freq) {
            priority_queue<long long, vector<long long>, greater<long long>> heap(freq.begin(), freq.end());
            long long cost = 0;
            while (heap.size() > 1) {
                long long a = heap.top(); heap.pop();   // the two smallest
                long long b = heap.top(); heap.pop();
                cost += a + b;                          // joining them costs their sum
                heap.push(a + b);                       // and the result joins the pile
            }
            return cost;
        }
    };

    Python

    import heapq
    
    class Solution:
        def huffmanBits(self, freq: list[int]) -> int:
            heap = list(freq)
            heapq.heapify(heap)
            cost = 0
            while len(heap) > 1:
                a, b = heapq.heappop(heap), heapq.heappop(heap)   # the two smallest
                cost += a + b                       # joining them costs their sum
                heapq.heappush(heap, a + b)         # and the result joins the pile
            return cost

    Common mistakes

    • Sorting once and summing, ignoring that joined nodes re-enter the order.
    • Using 32-bit totals.

    Similar problems