Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a priority queue for Huffman nodes.
DSA Java
PriorityQueue<Node> pq = new PriorityQueue<>([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using a comparator that orders frequencies descending.
Using addition or multiplication instead of subtraction.
✗ Incorrect
The priority queue should order nodes by frequency ascending, so the comparator subtracts frequencies.
2fill in blank
mediumComplete the code to build the Huffman tree by combining two lowest frequency nodes.
DSA Java
Node left = pq.poll();
Node right = pq.poll();
Node parent = new Node(null, left.freq + right.freq);
parent.left = left;
parent.right = right;
pq.[1](parent);Attempts:
3 left
💡 Hint
Common Mistakes
Using poll() which removes instead of adding.
Using peek() which only views the element.
✗ Incorrect
After creating the parent node, it must be added back to the priority queue.
3fill in blank
hardFix the error in the recursive method to generate Huffman codes.
DSA Java
void generateCodes(Node root, String code) {
if (root == null) return;
if (root.ch != null) {
codes.put(root.ch, code);
} else {
generateCodes(root.left, code [1] "0");
generateCodes(root.right, code [1] "1");
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using arithmetic operators other than + for strings.
Not concatenating the code string properly.
✗ Incorrect
To build the code string, concatenate '0' or '1' to the current code using + operator.
4fill in blank
hardFill both blanks to create a map of character frequencies from a string.
DSA Java
Map<Character, Integer> freqMap = new HashMap<>(); for (char c : text.toCharArray()) { freqMap.put(c, freqMap.getOrDefault(c, [1]) [2] 1); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as default causes off-by-one errors.
Using subtraction instead of addition.
✗ Incorrect
If character not present, default count is 0, then add 1 to update frequency.
5fill in blank
hardFill all three blanks to create a Huffman code map filtering only codes with length > 0.
DSA Java
Map<Character, String> filteredCodes = codes.entrySet().stream() .filter(e -> e.getValue().length() [1] 0) .collect(Collectors.toMap( e -> e.getKey(), e -> e.getValue().[2](), (a, b) -> a, [3]));
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > in filter.
Forgetting parentheses on toUpperCase method.
Not providing a map supplier in collect.
✗ Incorrect
Filter codes with length > 0, convert values to uppercase, collect into a new HashMap.
