Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a frequency map from the input string.
DSA Go
freq := make(map[rune]int) for _, ch := range input { freq[ch] [1] 1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of '+=' causes the count to reset.
Using '++' is invalid for map values in Go.
✗ Incorrect
We use '+=' to increment the count of each character in the frequency map.
2fill in blank
mediumComplete the code to define the Huffman tree node struct with frequency and character fields.
DSA Go
type Node struct {
char rune
freq int
left *Node
right *Node
}
func NewNode(c rune, f int) *Node {
return &Node{char: c, freq: [1]
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning freq: c or freq: char causes type errors.
Using freq without parameter causes undefined variable error.
✗ Incorrect
The frequency field should be initialized with the parameter 'f'.
3fill in blank
hardFix the error in the priority queue comparison function for Huffman nodes.
DSA Go
func (pq PriorityQueue) Less(i, j int) bool {
return pq[i].freq [1] pq[j].freq
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' reverses the priority order.
Using '==' does not define a strict ordering.
✗ Incorrect
The priority queue should order nodes by increasing frequency, so use '<'.
4fill in blank
hardFill both blanks to build the Huffman tree by merging two smallest nodes.
DSA Go
left := heap.Pop(&pq).(*Node)
right := heap.Pop(&pq).(*Node)
merged := &Node{freq: left.freq [1] right.freq, left: left, right: [2]
heap.Push(&pq, merged)Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' causes incorrect frequency calculation.
Assigning left instead of right to the right child pointer.
✗ Incorrect
We sum frequencies with '+' and assign the right child to 'right'.
5fill in blank
hardFill all three blanks to generate Huffman codes recursively.
DSA Go
func generateCodes(node *Node, code string, codes map[rune]string) {
if node == nil {
return
}
if node.left == nil && node.right == nil {
codes[[1]] = code
return
}
generateCodes(node.[2], code + "[3]", codes)
generateCodes(node.right, code + "1", codes)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'right' instead of 'left' for the first recursive call.
Appending '1' instead of '0' for left child.
✗ Incorrect
We assign code to the character, then recurse left with '0' appended.
