Compute minimal cost to merge numbers
Company: Morgan Stanley
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Take-home Project
Quick Answer: Compute minimal cost to merge numbers evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- 0 <= n (array length); return 0 when n <= 1.
- Each element is a positive integer.
- The accumulated total cost may exceed 32-bit range; use 64-bit integers in Java/C++.
- Merges continue until exactly one number remains.
Examples
Input: ([4, 3, 2, 6],)
Expected Output: 29
Explanation: Merge 2+3=5 (cost 5), then 4+5=9 (cost 9), then 6+9=15 (cost 15). Total 5+9+15 = 29.
Input: ([1, 2, 3, 4],)
Expected Output: 19
Explanation: Merge 1+2=3 (cost 3), then 3+3=6 (cost 6), then 4+6=10 (cost 10). Total 3+6+10 = 19.
Input: ([20, 4, 8, 2],)
Expected Output: 54
Explanation: Merge 2+4=6 (cost 6), then 6+8=14 (cost 14), then 14+20=34 (cost 34). Total 6+14+34 = 54.
Input: ([5],)
Expected Output: 0
Explanation: A single element needs no merge, so the cost is 0.
Input: ([],)
Expected Output: 0
Explanation: An empty array needs no merge, so the cost is 0.
Input: ([7, 7],)
Expected Output: 14
Explanation: Only one merge possible: 7+7=14 (cost 14). Duplicates handled naturally.
Input: ([1, 1, 1, 1],)
Expected Output: 8
Explanation: Merge 1+1=2 (cost 2), 1+1=2 (cost 2), then 2+2=4 (cost 4). Total 2+2+4 = 8.
Input: ([1000000, 1000000, 1000000],)
Expected Output: 5000000
Explanation: Merge 1000000+1000000=2000000 (cost 2000000), then 2000000+1000000=3000000 (cost 3000000). Total 5000000 — large sums require 64-bit accumulation.
Hints
- Think about how many times each original value gets added into the running cost — it equals its depth in the merge tree.
- To minimize a weighted sum where weight = depth, keep the smallest values deepest: always combine the two smallest numbers first.
- A min-heap (priority queue) lets you repeatedly extract the two smallest values in O(log n) and push their sum back.