Minimum Cost Tree From Leaf Values solution explained
Minimum Cost Tree From Leaf Values gives you a row of positive integers that must be the leaves of a binary tree, in order, where every internal node has two children and is worth the largest leaf on its left times the largest leaf on its right. You want the smallest possible total of the internal nodes. An interval DP tries every split point of every range in O(n³). The faster answer is greedy: the smallest leaf should be paired with its smaller neighbor and then forgotten, and a decreasing stack does that for every leaf in O(n).
By Evin JohnPublished 7 min read
The problem, restated
You get an array of positive integers. Build any binary tree in which every node has zero or two children and the leaves, read from left to right, are exactly the array. Each internal node is assigned the product of the largest leaf in its left subtree and the largest leaf in its right subtree. Return the smallest possible sum of all internal node values.
| Leaves | Minimum sum | Note |
|---|---|---|
| [4, 1, 3, 2] | 21 | Pair 1 with 3, then 2 with 3, then 3 with 4 |
| [3, 5, 2] | 25 | Both tree shapes cost 25 |
| [1, 2, 3, 4] | 20 | Increasing: each leaf joins the next one up |
| [5, 5] | 25 | One internal node |
| [7] | 0 | A single leaf has no internal nodes |
What the interviewer is checking
Most candidates spot the interval DP, because "choose where the root splits the leaves" is a familiar shape. That is a solid answer. The stronger signal is noticing that each internal node's value only depends on two maximums, which leads to the greedy observation and the monotonic stack. Interviewers often accept the DP and then ask "can you do better?" to see whether you can reason about which leaf should be combined first.
Questions to settle
- Can leaves be reordered? No. In-order traversal must give the array exactly.
- Are values positive? Yes, which the greedy relies on.
- Is the answer the sum of internal nodes only? Yes; leaves themselves add nothing.
Interval DP
The root splits the leaves into a left part i..k and a right part k + 1..j. The two subtrees are independent, so the cost of a range is the best split's left cost plus right cost plus the root value, which is the largest leaf on the left times the largest leaf on the right. Precompute range maximums so each term is O(1).
def mct_interval(leaves):
n = len(leaves)
top = [[0] * n for _ in range(n)]
for i in range(n):
top[i][i] = leaves[i]
for j in range(i + 1, n):
top[i][j] = max(top[i][j - 1], leaves[j])
cost = [[0] * n for _ in range(n)]
for span in range(2, n + 1):
for i in range(n - span + 1):
j = i + span - 1
cost[i][j] = min(
cost[i][k] + cost[k + 1][j] + top[i][k] * top[k + 1][j]
for k in range(i, j)
)
return cost[0][n - 1] if n else 0The greedy observation
Take the smallest leaf, a. At some point it is merged with something next to it, and from then on it never matters again, because the merged subtree's maximum is the other side's maximum, which is at least a. The merge that consumes a costs a times the maximum of the subtree it joins, and that subtree contains one of a's two neighbors, so the cost is at least a times the smaller neighbor. Pairing a directly with its smaller neighbor achieves exactly that lower bound and leaves the rest of the row unchanged. So remove a, pay a × min(left neighbor, right neighbor), and repeat on the shorter row.
def mct_remove_smallest(leaves):
row = list(leaves)
total = 0
while len(row) > 1:
i = row.index(min(row))
if i == 0:
partner = row[1]
elif i == len(row) - 1:
partner = row[-2]
else:
partner = min(row[i - 1], row[i + 1])
total += row[i] * partner
row.pop(i)
return totalThe monotonic stack: O(n)
Scanning left to right, keep a stack of leaves in decreasing order. When the next leaf x is at least the top of the stack, the top is a local minimum: its left neighbor is the element below it on the stack and its right neighbor is x, both at least as large. Pop it and pay top × min(below, x). After the scan, the stack is decreasing, so each remaining leaf's smaller neighbor is the one below it; pop from the top and pay each one times the next.
def mct_stack(leaves):
total = 0
stack = [float("inf")]
for x in leaves:
while stack[-1] <= x:
low = stack.pop()
total += low * min(stack[-1], x)
stack.append(x)
while len(stack) > 2:
total += stack.pop() * stack[-1]
return totalfunction mctFromLeafValues(leaves) {
let total = 0;
const stack = [Infinity];
for (const x of leaves) {
while (stack[stack.length - 1] <= x) {
const low = stack.pop();
total += low * Math.min(stack[stack.length - 1], x);
}
stack.push(x);
}
while (stack.length > 2) {
total += stack.pop() * stack[stack.length - 1];
}
return total;
}Trace on [4, 1, 3, 2]
| Step | Stack after | Paid | Running total |
|---|---|---|---|
| Push 4 | [4] | 0 | |
| Push 1 | [4, 1] | 0 | |
| See 3: pop 1, pay 1 × min(4, 3) | [4, 3] | 3 | 3 |
| Push 2 | [4, 3, 2] | 3 | |
| End: pop 2, pay 2 × 3 | [4, 3] | 6 | 9 |
| End: pop 3, pay 3 × 4 | [4] | 12 | 21 |
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Try every tree shape | Exponential (Catalan number of shapes) | O(n) stack |
| Interval DP | O(n³) | O(n²) |
| Remove the smallest, repeatedly | O(n²) | O(n) |
| Monotonic stack | O(n) | O(n) |
Edge cases
- A single leaf: the answer is 0 and every version must handle it.
- Equal values next to each other: the stack pops on <=, so ties are paired correctly.
- Strictly increasing leaves: every push pops the previous leaf.
- Strictly decreasing leaves: nothing pops during the scan; all the work happens at the end.
Common mistakes
- Pairing the smallest leaf with its larger neighbor, or always with the left one.
- Sorting the leaves, which breaks the in-order requirement.
- In the DP, recomputing range maximums inside the triple loop, which adds another factor of n.
- Using < instead of <= in the stack, which leaves equal neighbors on the stack and can still give the right total but makes the invariant harder to explain.
- Forgetting the final loop that combines what is left on the stack.
How to explain it out loud
Fictional example
- Candidate
- The root splits the leaves into two contiguous parts, so an interval DP over split points works in n cubed. Root value is the max on the left times the max on the right.
- Interviewer
- Can you do better?
- Candidate
- The smallest leaf gets merged with a neighbor at some point and then never matters again. Merging it costs it times something at least as big as one neighbor, so the cheapest is its smaller neighbor. I can do that greedily.
- Candidate
- A decreasing stack finds local minimums as I scan: when a new value is at least the top, the top's neighbors are the one below it and the new value. That makes it linear.
Related problems
Palindrome Partitioning II is another problem about where to cut a sequence. Minimum Insertion Steps to Make a String Palindrome is an interval DP over a string. Guess Number Higher or Lower II tries every split of a range with a minimax twist, and Maximal Rectangle is a good place to practice monotonic stacks.
Practicing with Natively
Many candidates know the stack code but cannot say why it is correct, and that explanation is what interviewers ask for. Practice the greedy argument in a mock session on Mac or Windows, with Natively transcribing so you can review how clearly it came out. After you have your own solution, Natively can read the problem from a screenshot and suggest an approach to check yours against. See the AI interview assistant.
Questions people ask
How do you solve Minimum Cost Tree From Leaf Values?
Repeatedly remove the smallest leaf, paying it times the smaller of its two neighbors. A decreasing stack does this in one pass: pop while the top is at most the next value, paying top times min(new top, value).
Why pair the smallest leaf with its smaller neighbor?
The smallest leaf is merged once and never matters again, and that merge costs at least the leaf times one neighbor. Pairing it with the smaller neighbor reaches that lower bound.
Is there a DP solution?
Yes. cost(i, j) = min over split k of cost(i, k) + cost(k + 1, j) + max(i..k) times max(k + 1..j). It runs in O(n cubed).
What is the time complexity of the stack solution?
O(n) time and O(n) memory, since every leaf is pushed and popped once.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
