Challenge - 5 Problems
Huffman Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Huffman Tree Construction
What is the output of the following code that builds a Huffman tree and prints the root frequency?
DSA Python
import heapq class Node: def __init__(self, freq, char=None, left=None, right=None): self.freq = freq self.char = char self.left = left self.right = right def __lt__(self, other): return self.freq < other.freq def build_huffman_tree(freq_map): heap = [Node(freq, char) for char, freq in freq_map.items()] heapq.heapify(heap) while len(heap) > 1: left = heapq.heappop(heap) right = heapq.heappop(heap) merged = Node(left.freq + right.freq, None, left, right) heapq.heappush(heap, merged) return heap[0] freq_map = {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45} root = build_huffman_tree(freq_map) print(root.freq)
Attempts:
2 left
💡 Hint
Sum all frequencies to find the root frequency.
✗ Incorrect
The root frequency is the sum of all character frequencies: 5+9+12+13+16+45 = 100.
🧠 Conceptual
intermediateHuffman Encoding Bit Length Calculation
Given the frequencies {'x': 3, 'y': 3, 'z': 4}, what is the total number of bits required to encode the string "xyzxyz" using Huffman encoding?
Attempts:
2 left
💡 Hint
Calculate the Huffman codes and multiply by character counts.
✗ Incorrect
The Huffman codes assign 2 bits for 'x' and 'y', and 1 bit for 'z'. Encoding "xyzxyz" requires 2*2 + 2*2 + 2*1 = 10 bits.
🔧 Debug
advancedIdentify the Error in Huffman Encoding Function
What error does the following code raise when trying to encode a string using Huffman codes?
DSA Python
def encode_string(s, codes): result = '' for ch in s: result += codes[ch] return result codes = {'a': '0', 'b': '10', 'c': '11'} print(encode_string('abcx', codes))
Attempts:
2 left
💡 Hint
Check if all characters in the string have codes.
✗ Incorrect
The character 'x' is not in the codes dictionary, so accessing codes['x'] raises a KeyError.
🚀 Application
advancedHuffman Decoding Result
Given the Huffman codes {'a': '0', 'b': '10', 'c': '11'}, what is the decoded string of the bit sequence '0110'?
Attempts:
2 left
💡 Hint
Decode bits step by step using the codes.
✗ Incorrect
The bit sequence '0110' can be split as '0' (a), '10' (b), '10' (b) to get 'abb'.
🧠 Conceptual
expertMinimum Weighted Path Length in Huffman Tree
For a set of characters with frequencies {A: 1, B: 1, C: 2, D: 3, E: 5}, what is the minimum weighted path length (sum of frequency * code length) of the Huffman encoding?
Attempts:
2 left
💡 Hint
Build the Huffman tree and calculate sum(freq * depth).
✗ Incorrect
The optimal Huffman tree assigns code lengths so that the sum of frequency times code length is 13.
