Huffman Encoding in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to build a Huffman tree changes as the number of characters grows.
How does the process of encoding scale with more characters?
Analyze the time complexity of the following code snippet.
function buildHuffmanTree(freqMap: Map) {
const heap = new MinHeap();
for (const [char, freq] of freqMap.entries()) {
heap.insert(new Node(char, freq));
}
while (heap.size() > 1) {
const left = heap.extractMin();
const right = heap.extractMin();
const merged = new Node(null, left.freq + right.freq, left, right);
heap.insert(merged);
}
return heap.extractMin();
}
This code builds a Huffman tree by repeatedly combining the two smallest frequency nodes until one tree remains.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Removing two smallest nodes and inserting their merged node back into the heap.
- How many times: This happens about n-1 times, where n is the number of unique characters.
Each insertion or removal from the heap takes time related to the heap size, which grows with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 x log 10 = 33 operations |
| 100 | About 100 x log 100 = 664 operations |
| 1000 | About 1000 x log 1000 = 9965 operations |
Pattern observation: As n grows, the operations grow a bit faster than n but much slower than n squared.
Time Complexity: O(n log n)
This means the time to build the Huffman tree grows a little more than linearly as the number of characters increases.
[X] Wrong: "Building the Huffman tree takes only linear time because we just combine nodes."
[OK] Correct: Each combination involves heap operations that take time proportional to log of the heap size, so the total time is more than just linear.
Understanding how Huffman encoding scales helps you explain efficient data compression and priority queue use, which are common in coding challenges.
"What if we used a simple sorted list instead of a heap for managing nodes? How would the time complexity change?"
Practice
Solution
Step 1: Understand Huffman Encoding goal
Huffman Encoding aims to reduce the total bits used by giving shorter codes to frequent characters.Step 2: Compare options with this goal
Only To assign shorter codes to more frequent characters matches this goal. Others describe different or incorrect purposes.Final Answer:
To assign shorter codes to more frequent characters -> Option DQuick Check:
Huffman Encoding = shorter codes for frequent chars [OK]
- Thinking Huffman assigns equal length codes
- Confusing Huffman with encryption
- Assuming it sorts characters alphabetically
Solution
Step 1: Identify priority queue needs
Huffman Encoding requires repeatedly extracting the smallest frequency node efficiently.Step 2: Choose data structure for efficient min extraction
Min-Heap allows quick access and removal of the smallest element, ideal for this use.Final Answer:
Min-Heap -> Option BQuick Check:
Priority queue = Min-Heap for Huffman [OK]
- Using Set which has no order
- Using Map which is key-value, not priority queue
- Using Array without sorting is inefficient
Solution
Step 1: Build Huffman tree from frequencies
Combine lowest frequencies stepwise: (a=5,b=9)->14, (c=12,d=13)->25, then combine 14 and 16 (e) and so on, finally f=45 is highest frequency with shortest code.Step 2: Assign codes from tree paths
Left edges as '0', right edges as '1' produce codes: f='0', c='100', d='101', a='1100', b='1101', e='111'.Final Answer:
{ 'f': '0', 'c': '100', 'd': '101', 'a': '1100', 'b': '1101', 'e': '111' } -> Option CQuick Check:
Highest freq 'f' gets shortest code '0' [OK]
- Assigning codes without building tree
- Mixing left/right edge bits
- Ignoring frequency order
class Node {
constructor(public char: string | null, public freq: number, public left: Node | null = null, public right: Node | null = null) {}
}
function insertNode(queue: Node[], node: Node) {
queue.push(node);
queue.sort((a, b) => a.freq - b.freq);
}
// Usage
const queue: Node[] = [];
insertNode(queue, new Node('a', 5));
insertNode(queue, new Node('b', 9));
insertNode(queue, new Node(null, 14));
Solution
Step 1: Analyze insertNode function
It pushes a node then sorts the entire queue array by frequency each time.Step 2: Identify inefficiency
Sorting the whole array on every insertion is inefficient for large data; a Min-Heap is better for priority queue operations.Final Answer:
Sorting after push is inefficient; use a Min-Heap instead -> Option AQuick Check:
Priority queue needs efficient insert and extract [OK]
- Thinking sorting order is wrong
- Missing inefficiency of sorting whole array
- Confusing type annotations as bug
Solution
Step 1: Calculate frequencies
String "aaabbc" has frequencies: a=3, b=2, c=1.Step 2: Build Huffman tree and assign codes
Lowest freq c=1 and b=2 combine first, then with a=3. Assign codes: a='0', b='10', c='11'.Step 3: Encode string using codes
Encoding "aaabbc" = a(3 times) '0 0 0', b(2 times) '10 10', c(1 time) '11' -> '000101011'.Final Answer:
Codes: {a:'0', b:'10', c:'11'}, Encoded: '000101011' -> Option AQuick Check:
Freq order a>b>c matches codes and encoding [OK]
- Mixing code assignments
- Encoding with wrong code bits
- Ignoring frequency order in code assignment
Ready to prove it?
Pass the test and this pattern moves unknown
