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))- A. 72 72 89
- B. 80 80 89
- C. 72 80 89
- 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).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- You must count pairs i < j with a[i] + a[j] ≤ T for n ≤ 2·10⁵ values up to 10⁹ in absolute value (time limit 1 s). Which plan passes?
- A service stores n = 10⁵ integer keys in a chained hash table with m = 1000 buckets and h(k) = k mod m. An attacker sends keys that are…
- An empty queue performs: enqueue 7, enqueue 2, enqueue 9, dequeue, enqueue 4, dequeue. Which element is now at the front?
- In a doubly linked list you are given a pointer to a node X somewhere in the middle. What is the time to delete X?
- A hash table has 7 slots and uses h(k) = k mod 7. In which slot is the key 50 placed if that slot is empty?
- Operators have the usual precedence ( and / above + and −, all left-associative). What is the postfix form of A (B + C) / D − E?