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?- A. 141
- B. 171
- C. 120
- 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
- Problem: Balloons span horizontal intervals [start, end]; an arrow shot at x bursts every balloon with start ≤ x ≤ end. Find the minimum…
- Problem: A knight walks from the top-left to the bottom-right cell moving only right or down; each cell adds its value to his health…
- Problem: Can s3 be formed by interleaving s1 and s2 (keeping each string's own order)? python def inter(s1, s2, s3): if len(s1) + len(s2)…
- Problem: Count palindromic substrings (by position, so equal strings at different places count separately) by expanding around every…
- Problem: Cut a rod of length 7 into integer pieces to maximise total price, where price[i] is the price of a piece of length i + 1…
- Problem: Envelopes [w, h] nest only if both dimensions are strictly smaller. Find the longest nesting chain by sorting and then running…