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 Published 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.

Examples written for this page (outputs printed by the code below)
LeavesMinimum sumNote
[4, 1, 3, 2]21Pair 1 with 3, then 2 with 3, then 3 with 4
[3, 5, 2]25Both tree shapes cost 25
[1, 2, 3, 4]20Increasing: each leaf joins the next one up
[5, 5]25One internal node
[7]0A single leaf has no internal nodes
Examples written for this page (outputs printed by the code below). Scroll sideways on a small screen.

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 0
Python: interval DP with a range-max table. O(n^3).

The 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 total
Python: remove the smallest leaf repeatedly. O(n^2).

The 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 total
Python: decreasing stack with a large sentinel at the bottom.
function 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;
}
JavaScript: the same stack. Infinity works as the sentinel.

Trace on [4, 1, 3, 2]

Stack shown bottom to top, sentinel omitted
StepStack afterPaidRunning total
Push 4[4]0
Push 1[4, 1]0
See 3: pop 1, pay 1 × min(4, 3)[4, 3]33
Push 2[4, 3, 2]3
End: pop 2, pay 2 × 3[4, 3]69
End: pop 3, pay 3 × 4[4]1221
Stack shown bottom to top, sentinel omitted. Scroll sideways on a small screen.

Complexity

n leaves
ApproachTimeExtra memory
Try every tree shapeExponential (Catalan number of shapes)O(n) stack
Interval DPO(n³)O(n²)
Remove the smallest, repeatedlyO(n²)O(n)
Monotonic stackO(n)O(n)
n leaves. Scroll sideways on a small screen.

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

From DP to greedy
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.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP