GATE / CS ARCHIVE

SIMILAR QUESTIONS / ALGORITHMS

Repeatedly combine the two shortest sequences

2 questions solved the same way, newest first. Back to Algorithms

How these are solved

The greedy optimal merge tree repeatedly combines two smallest current lengths. 1999 charges merged records moved, m+n;

2 marks · NAT
Report issue

Greedy Algorithms

Question 38, GATE 2014: Sorted sequences P,Q,R,S,T have lengths 20,24,30,35,50. Merge two sequences at a time until one remains. Find the minimum possible worst-case total number of comparisons.
Tap to enlarge
Answer & solution

Official answer: 358

1. Set up the reasoning. A merge of lengths a and b needs a+b-1 comparisons in the worst case. The optimal merge-pattern rule repeatedly joins the two currently shortest sequences, reinserting the combined length.

2. Derive the result. Optimal merging repeatedly combines the two shortest lists: 20+24=44, 30+35=65, 44+50=94, 65+94=159. A merge of lengths a, b uses at most a+b−1 comparisons, so total 43+64+93+158=358. The shortest-pair rule minimizes weighted leaf depth, as in Huffman coding.

3. Check the interpretation. Track lengths after each merge: 44 joins the queue after 20 and 24; 65 after 30 and 35; then combine 44 and 50. Subtract one comparison for each of the four merges, not just once from the final length.

Original paper, page 39 · Answer key

2 marks · MSQ
Report issue

Optimal merge cost

Greedy Algorithms

Question 2.20, GATE 1999: Merge file lengths 10,20,15,5,25 with pairwise merging; cost is records moved. Choose165,90,75,65.
Tap to enlarge
Select all that apply
Answer & solution

Answer: A: 165 (no official key was published)

Always merge the two shortest remaining files, as in the optimal merge/Huffman construction. Merge5+10=15, costing 15; then 15+15=30, costing 30; then 20+25=45, costing 45; finally 30+45=75, costing 75. Total cost is 15+30+45+75=165. The greedy choice is optimal because two smallest weights can occupy deepest sibling leaves of an optimal merge tree, after which contracting them leaves the same problem on fewer files. Counting only 75 ignores repeated moves through intermediate merges.

Original paper, page 5