What is Huffman Encoding
Given arrays chars and freq, where freq[i] is the frequency of chars[i], construct Huffman codes and return the code for each character.
Required Output: Prefix-free binary strings where higher-frequency characters generally get shorter codes.
Example 1:
Input: chars = [a,b,c,d,e,f], freq = [5,9,12,13,16,45] Output (one valid set): f:0, c:100, d:101, a:1100, b:1101, e:111 Explanation: More frequent f gets shortest code.
Example 2:
Input: chars = [A,B,C,D], freq = [10,15,30,16] Output (one valid set): C:0, D:10, A:110, B:111 Explanation: Codes may differ by tie-breaking but weighted cost stays minimal.
Constraints:
Heap Priority: Always merge the two smallest frequencies first.
Encoding: Left child adds bit 0, right child adds bit 1.
Compression Benefit: Frequent characters stay near root, reducing total bits.
Selection State
Heap not initialized.
Codes will appear after complete tree build.
Step Info
Waiting to build...
Algorithm & Pseudocode
| Aspect | Complexity |
|---|---|
| Build Heap + Merges | O(n log n) |
| DFS Code Generation | O(n) |
| Space | O(n) |
Implementation
Heap Operations: extractMin and insertMin maintain smallest frequencies at top.
Merge Step: Internal parent node frequency is sum of two children.
Code Generation: DFS accumulates 0/1 path bits from root to leaves.