2Brute2Best
🔥0

Huffman Coding

Medium·GeeksforGeeks Pro OnlyMedium
GeeksforGeeks
01

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.

Input

A string s of distinct characters, and an array f of the same length with the frequency of each character.

Output

A list of strings: the code of each character, in preorder of the Huffman tree.

Example 1
Input: s = "abcdef", f = [5, 9, 12, 13, 16, 45]
Output: [0, 100, 101, 1100, 1101, 111]

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.

Constraints
  • • 1 ≤ s.size() = f.size() ≤ 26
02

Pattern Recognition Clues

Recognising these key signals in the problem description immediately identifies the pattern:

“build a Huffman tree”
→ The tree is built bottom-up by merging, so each step needs the two smallest weights.
“codes with the fewest total bits”
→ A letter's cost is its frequency times its depth. The total of the merged weights is that cost.
“tie rule about the earlier letter”
→ Ties don't change the total cost, but they do change the codes. The statement fixes one answer.
03

Approach Complexity Ladder

Brute Force — each round, scan for the two smallest treesO(N²)O(N)

Each round, scan every remaining tree for the two smallest (with the tie rule) and merge them

Optimal — min-heap: merge the two smallest treesO(N log N)O(N)

Min-heap of trees by (weight, earliest letter); pop the two smallest, merge them, and push the result back

Brute Force Intuition

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:

The best choice changes as you go — keep candidates in a heap and always pop the current best.
Remember this · Greedy
Trigger
Maximise count / minimise cost with a natural "best next step", sorting makes the choice obvious, reachability.
Think
Is there a choice I can always make safely without looking ahead?
Key question
Why can't the greedy choice be worse than the optimal one? (Try to break it with a small example.)
Brute2Best Pro Content

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.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Greedy translate into production architectures and low-level memory mechanics.