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?- A. 18 37
- B. 36 37
- C. 36 36
- 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
- Problem: Rain on a height grid flows to a neighbour with height ≤ the current cell. The west/north edge touches one sea, the east/south…
- Problem: A recursive routine splits a problem of size n into parts n/3 and 2n/3 and does n extra work: W(n) = W(n/3) + W(2n/3) + n. The…
- Problem: Find the bug: Dijkstra (finalising a node when it is popped) is run on a graph with one negative edge and compared with…
- Problem: Count integers in [1, N] whose decimal digits have no two adjacent equal digits, using digit DP with states (position, previous…
- Problem: Count all valid topological orderings of a small DAG (n ≤ 20) with a DP over subsets: from a set of already placed nodes, place…
- Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM…