Huffman Coding
Problem Statement
You get a string s of distinct characters, and an array f where f[i] is how often s[i] appears. Build a Huffman tree from these frequencies, and return the code of every character.
In the tree, a left edge adds 0 and a right edge adds 1. Return the codes in preorder: the left side of the tree before the right side.
Tie rule: when two tree nodes have the same frequency, the node whose subtree contains the character that comes earlier in s goes on the left, and the other goes on the right. Otherwise the node with the smaller frequency goes on the left.
A string s of distinct characters, and an array f of the same length with the frequency of each character.
A list of strings: the code of each character, in preorder of the Huffman tree.
The codes are f = 0, c = 100, d = 101, a = 1100, b = 1101 and e = 111. Reading the tree left to right gives this order.
- • 1 ≤ s.size() = f.size() ≤ 26
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Each round, scan every remaining tree for the two smallest (with the tie rule) and merge them
Min-heap of trees by (weight, earliest letter); pop the two smallest, merge them, and push the result back
Keep a list of trees, one per letter. Each round, scan the whole list for the smallest tree, then for the second smallest. Merge the two into one tree, with the smaller on the left, and add it to the list. Repeat until one tree is left, then walk it in preorder.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Greedy translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.