Complete the code to create a frequency map from the input string.
const frequencyMap: Record<string, number> = {};
for (const char of input) {
frequencyMap[char] = (frequencyMap[char] || 0) [1] 1;
}We add 1 to the current count for each character to build the frequency map.
Complete the code to sort the nodes by frequency in ascending order.
nodes.sort((a, b) => a.frequency [1] b.frequency);Subtracting frequencies sorts the array in ascending order.
Fix the error in the code that merges two nodes into a new parent node.
const mergedNode = {
character: null,
frequency: left.frequency [1] right.frequency,
left: left,
right: right
};The frequency of the merged node is the sum of the two child nodes' frequencies.
Fill both blanks to assign codes recursively to the Huffman tree nodes.
function assignCodes(node: Node | null, code: string) {
if (!node) return;
if (node.character !== null) {
codes[node.character] = code;
}
assignCodes(node.[1], code + '0');
assignCodes(node.[2], code + '1');
}We traverse left child with '0' and right child with '1' to assign codes.
Fill all three blanks to build the Huffman tree by merging nodes until one remains.
while (nodes.length > 1) { const left = nodes.shift(); const right = nodes.shift(); const mergedNode = { character: null, frequency: left.frequency [1] right.frequency, left: left, right: right }; nodes.push(mergedNode); nodes.sort((a, b) => a.frequency [2] b.frequency); } const root = nodes.[3]();
We sum frequencies to merge nodes, sort ascending by subtracting frequencies, and finally pop the root node.