Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i, j] with prefix sums), and compare with greedily merging the cheapest adjacent pair.

Problem: Adjacent piles in a row are merged two at a time; merging costs the combined size. Minimise the total cost (interval DP over [i, j] with prefix sums), and compare with greedily merging the cheapest adjacent pair.
def merge_cost(p):
    n = len(p); pre = [0]
    for x in p: pre.append(pre[-1] + x)
    dp = [[0] * n for _ in range(n)]
    for length in range(2, n + 1):
        for i in range(n - length + 1):
            j = i + length - 1
            dp[i][j] = min(dp[i][k] + dp[k + 1][j] for k in range(i, j)) + pre[j + 1] - pre[i]
    return dp[0][n - 1]
def greedy_merge(p):
    p = list(p); cost = 0
    while len(p) > 1:
        i = min(range(len(p) - 1), key=lambda k: p[k] + p[k + 1])
        s = p[i] + p[i + 1]; cost += s; p[i:i + 2] = [s]
    return cost
print(merge_cost([6, 4, 3, 5]), greedy_merge([6, 4, 3, 5]))
What is printed?
  1. A. 18 37
  2. B. 36 37
  3. C. 36 36
  4. D. 37 37

Correct answer: B. 36 37

The last merge of [i..j] combines some split [i..k] and [k+1..j] and always costs sum(i..j), so dp[i][j] = min over k + range sum; O(n³) (Knuth's optimisation gives O(n²)). Optimal: (6+4) = 10, (3+5) = 8, then 18 → 36. Greedy merges 4+3 = 7 first, then 7+5 = 12, then 6+12 = 18 → 37. Huffman's heap greedy only works when ANY two piles may be merged, not just adjacent ones.

More Coding Interview Problems questions

Exams that ask this topic