Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length).

Problem: Build a Huffman code for symbol frequencies and report the total number of bits for the encoded message (Σ freq × code length).
import heapq
def huff(f):
    h = list(f); heapq.heapify(h); cost = 0
    while len(h) > 1:
        a, b = heapq.heappop(h), heapq.heappop(h)
        cost += a + b; heapq.heappush(h, a + b)
    return cost
print(huff([2, 3, 7, 10, 15, 20]))
What is printed?
  1. A. 141
  2. B. 171
  3. C. 120
  4. D. 131

Correct answer: D. 131

Merges: 2+3 = 5, 5+7 = 12, 10+12 = 22, 15+20 = 35, 22+35 = 57. The total of all merge costs equals Σ freq × depth: 5 + 12 + 22 + 35 + 57 = 131. A fixed 3-bit code would cost 57 × 3 = 171.

More Coding Interview Problems questions

Exams that ask this topic