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)- A. 224 300
- B. 224 100
- C. 230 300
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Longest common subsequence: what is the length and one LCS read back from the table (preferring the upper cell on ties)? python a, b =…
- Edit distance between "kitten" and "sitting", and between "intention" and "execution". What is printed? python def ed(a, b): prev =…
- Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?…
- What is printed? (level-order traversal of the BST built from these keys) python def insert(t, k): if t is None: return [k, None, None] i…
- What is printed? (inorder successor in a BST) python def insert(t, k): if t is None: return [k, None, None] i = 1 if k < t[0] else 2 t[i]…
- What is printed? (heap sort on a small array, showing the array after the first extraction) python def sift(a, i, n): while 2 i + 1 < n: c…