Data Structures & AlgorithmsHardProduct Company SDE pattern

Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text?

Huffman coding: frequencies a:5, b:9, c:12, d:13, e:16, f:45. What is the total number of bits to encode the text?
import heapq
f = [5, 9, 12, 13, 16, 45]
heapq.heapify(f); bits = 0
while len(f) > 1:
    x = heapq.heappop(f) + heapq.heappop(f)
    bits += x; heapq.heappush(f, x)
print(bits, sum([5, 9, 12, 13, 16, 45]) * 3)
  1. A. 224 300
  2. B. 224 100
  3. C. 230 300
  4. D. 200 300

Correct answer: A. 224 300

Each merge adds its sum once for every level the merged symbols move down, so the total encoded length is the sum of all merge costs: 14 + 25 + 30 + 55 + 100 = 224 bits, versus 100 × 3 = 300 bits with fixed 3-bit codes. O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic