Data Structures & AlgorithmsVery hardProduct company OA

Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right in sorted and in given order. What is printed?

Merging files costs the size of the result each time. Compare the greedy 'always merge the two smallest' (heap) with merging left to right in sorted and in given order. What is printed?
import heapq
def merge_cost(a):
    h = list(a); heapq.heapify(h); cost = 0
    while len(h) > 1:
        x = heapq.heappop(h) + heapq.heappop(h); cost += x; heapq.heappush(h, x)
    return cost
def left_to_right(a):
    s, cost = a[0], 0
    for x in a[1:]: s += x; cost += s
    return cost
a = [7, 5, 8, 6, 5]
print(merge_cost(a), left_to_right(sorted(a)), left_to_right(a))
  1. A. 72 72 89
  2. B. 80 80 89
  3. C. 72 80 89
  4. D. 72 80 72

Correct answer: C. 72 80 89

Each size is paid once per merge it takes part in, i.e. weighted by its depth in the merge tree – the Huffman argument shows merging the two smallest is optimal. Heap: 5+5 = 10, 6+7 = 13, 8+10 = 18, 13+18 = 31 → 72. Left to right on the sorted list keeps re-adding a growing prefix: 10, 16, 23, 31 → 80; sorting first does not make a chain optimal. In the given order: 12, 20, 26, 31 → 89. O(n log n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic