Challenge - 5 Problems
Huffman Encoding Master
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 Rust code that builds a Huffman tree from given character frequencies and prints the root node frequency?
DSA Rust
use std::collections::BinaryHeap; #[derive(Eq, PartialEq)] struct Node { freq: usize, left: Option<Box<Node>>, right: Option<Box<Node>>, } impl Ord for Node { fn cmp(&self, other: &Self) -> std::cmp::Ordering { other.freq.cmp(&self.freq) } } impl PartialOrd for Node { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } fn build_huffman_tree(freqs: &[(char, usize)]) -> Node { let mut heap = BinaryHeap::new(); for &(ch, freq) in freqs { heap.push(Node { freq, left: None, right: None }); } while heap.len() > 1 { let left = heap.pop().unwrap(); let right = heap.pop().unwrap(); let merged = Node { freq: left.freq + right.freq, left: Some(Box::new(left)), right: Some(Box::new(right)), }; heap.push(merged); } heap.pop().unwrap() } fn main() { let freqs = [('a', 5), ('b', 9), ('c', 12), ('d', 13), ('e', 16), ('f', 45)]; let root = build_huffman_tree(&freqs); println!("{}", root.freq); }
Attempts:
2 left
💡 Hint
Sum all frequencies to find the root node frequency.
✗ Incorrect
The root node frequency is the sum of all character frequencies: 5 + 9 + 12 + 13 + 16 + 45 = 100.
🧠 Conceptual
intermediateHuffman Encoding Code Length Calculation
Given a Huffman tree built from characters with frequencies [('x', 1), ('y', 1), ('z', 2)], what is the total length of the encoded string for the input "xyzzy"?
Attempts:
2 left
💡 Hint
Calculate the code length for each character based on the Huffman tree and multiply by its occurrences.
✗ Incorrect
The Huffman tree assigns 1 bit to 'z' (highest freq) and 2 bits to 'x' and 'y' (lowest freq). The string "xyzzy" has 1 'x' (2 bits), 2 'y' (4 bits), 2 'z' (2 bits), total 8 bits.
🔧 Debug
advancedIdentify the Error in Huffman Tree Node Comparison
What error will the following Rust code produce when compiling, and why?
```rust
use std::collections::BinaryHeap;
#[derive(Eq, PartialEq)]
struct Node {
freq: usize,
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.freq.cmp(&other.freq)
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option {
Some(self.cmp(other))
}
}
fn main() {
let mut heap = BinaryHeap::new();
heap.push(Node { freq: 5 });
heap.push(Node { freq: 3 });
while let Some(node) = heap.pop() {
println!("{}", node.freq);
}
}
```
Attempts:
2 left
💡 Hint
Check how the cmp function orders elements in BinaryHeap.
✗ Incorrect
No compilation or runtime error. BinaryHeap is a max-heap that pops the greatest element first. The `cmp` uses `self.freq.cmp(&other.freq)`, so higher freq is greater, printing 5 then 3.
🚀 Application
advancedHuffman Encoding Map Generation
Which option correctly generates a Huffman encoding map (character to bit string) from a given Huffman tree node in Rust?
DSA Rust
fn generate_codes(node: &Node, prefix: String, codes: &mut std::collections::HashMap<char, String>) {
if let Some(ch) = node.ch {
codes.insert(ch, prefix);
} else {
if let Some(ref left) = node.left {
generate_codes(left, prefix.clone() + "0", codes);
}
if let Some(ref right) = node.right {
generate_codes(right, prefix + "1", codes);
}
}
}Attempts:
2 left
💡 Hint
Check how prefix strings are built and stored for leaf nodes.
✗ Incorrect
Option D correctly clones prefix for left recursion and appends '0' or '1' accordingly, storing codes only at leaf nodes with characters.
🧠 Conceptual
expertOptimality of Huffman Encoding
Why is Huffman encoding considered optimal for prefix codes when encoding symbols with known frequencies?
Attempts:
2 left
💡 Hint
Think about average code length and prefix property.
✗ Incorrect
Huffman encoding minimizes the weighted average code length for symbols with given frequencies, ensuring no other prefix code can produce a shorter average length.
