Minimum Score Triangulation of Polygon solution explained
Minimum Score Triangulation of Polygon is solved with interval dynamic programming: the side joining the first and last corner belongs to exactly one triangle, so you try every possible third corner k, and the best cost for corners i to j is the best cost of i..k plus k..j plus the product of the three labels. Filling that table by gap length takes O(n³) time and O(n²) memory.
By Evin JohnPublished 8 min read
What the problem asks
Picture a convex polygon with n corners, listed in order around the shape. Every corner carries a positive whole number. You must divide the polygon into triangles by drawing diagonals between corners, with no two diagonals crossing. Any such division uses exactly n - 2 triangles. A triangle's score is its three corner numbers multiplied together, and the score of a division is the sum over its triangles. Find the lowest score any division can reach.
Geometry never actually enters the solution. Because the polygon is convex, every diagonal is legal, so the only thing that matters is which corners end up sharing a triangle. That turns a picture problem into a question about a list of numbers and the ways to bracket it.
| Corner values | Lowest total | How it is reached |
|---|---|---|
| [3, 7, 2] | 42 | Already a triangle: 3 × 7 × 2 |
| [2, 5, 3, 4] | 54 | Diagonal from the 2 to the 3: (2·5·3) + (2·3·4) = 30 + 24. The other diagonal costs 40 + 60 = 100 |
| [1, 4, 2, 6, 3] | 38 | Every triangle uses the 1: 8 + 12 + 18 |
| [9, 7, 8, 6, 7] | 1071 | Fanning out from the smallest value (6) gives 1092, so the cheapest corner is not always the hub |
Questions worth asking before you code: is n at least 3, or should a list of two values return 0? How large can the values get, and could the total overflow a 32-bit integer in the language you are using?
Why it gets asked
This is a clean test of whether a candidate can spot an interval structure when the prompt talks about shapes. Interviewers use it in later rounds to see three things: finding the one fixed choice that splits the problem (the triangle on a known side), defining a state that is just two indexes, and ordering the table so every smaller interval is ready before a bigger one needs it. If you have solved matrix chain multiplication, the recurrence will look familiar, and saying so out loud is a good signal.
The key observation
Take the side that joins corner 0 and corner n - 1. In any triangulation, that side is an edge of exactly one triangle. Call that triangle's third corner k, where 0 < k < n - 1. Once k is fixed, the triangle (0, k, n - 1) cuts the polygon into two smaller convex polygons: corners 0 through k, and corners k through n - 1. Those two pieces can be triangulated independently, and the best total is their two best totals plus the middle triangle's product.
The same argument works for any chord (i, j). So define cost(i, j) as the lowest score for the sub-polygon made of corners i, i + 1, ..., j, closed by the chord from i to j. Two adjacent corners form a single edge with nothing to cut, so cost(i, i + 1) = 0. For a wider interval, cost(i, j) is the minimum over every k strictly between i and j of cost(i, k) + cost(k, j) + v[i] · v[k] · v[j].
Slow approach: plain recursion
Coding the recurrence directly is a fine first draft, and it is correct. The trouble is the work. The same sub-polygon, for example corners 2 to 5, is reached through many different outer choices, and each time it is solved from scratch. The number of distinct triangulations of an n-gon is the Catalan number C(n - 2): 5 for a pentagon, 14 for a hexagon, 42 for seven corners, and roughly a factor of four more for each corner after that. Without caching, the recursion walks a tree of about that size.
def tri_score_slow(vals, i=0, j=None):
if j is None:
j = len(vals) - 1
if j - i < 2:
return 0 # an edge, nothing to cut
return min(
tri_score_slow(vals, i, k) + tri_score_slow(vals, k, j) + vals[i] * vals[k] * vals[j]
for k in range(i + 1, j)
)Main approach: fill the table by gap length
There are only about n²/2 distinct pairs (i, j), so store each answer once. A top-down version adds a cache to the function above. The bottom-up version below is just as short and avoids recursion depth limits: it fills cost[i][j] in order of the gap j - i, starting at 2 (a single triangle), so both halves of every split are already known when they are needed. The answer sits in cost[0][n - 1].
def min_score_triangulation(vals):
n = len(vals)
if n < 3:
return 0
cost = [[0] * n for _ in range(n)]
for gap in range(2, n): # gap = j - i
for i in range(n - gap):
j = i + gap
cost[i][j] = min(
cost[i][k] + cost[k][j] + vals[i] * vals[k] * vals[j]
for k in range(i + 1, j)
)
return cost[0][n - 1]function minScoreTriangulation(vals) {
const n = vals.length;
if (n < 3) return 0;
const cost = Array.from({ length: n }, () => new Array(n).fill(0));
for (let gap = 2; gap < n; gap++) {
for (let i = 0; i + gap < n; i++) {
const j = i + gap;
let best = Infinity;
for (let k = i + 1; k < j; k++) {
const total = cost[i][k] + cost[k][j] + vals[i] * vals[k] * vals[j];
if (total < best) best = total;
}
cost[i][j] = best;
}
}
return cost[0][n - 1];
}Trace [2, 5, 3, 4]. Gap 2 gives cost[0][2] = 2·5·3 = 30 and cost[1][3] = 5·3·4 = 60. Gap 3 tries k = 1, which is 0 + 60 + 2·5·4 = 100, and k = 2, which is 30 + 0 + 2·3·4 = 54. The minimum, 54, matches the table above.
Complexity
| Version | Time | Extra space | Comment |
|---|---|---|---|
| Plain recursion | Exponential (Catalan growth) | O(n) call stack | Only as an opening statement |
| Recursion with a cache on (i, j) | O(n³) | O(n²) plus O(n) stack | Fine; watch recursion limits in Python |
| Bottom-up table by gap | O(n³) | O(n²) | The version to write on the board |
The cubic bound comes from O(n²) states, each scanning up to n split points. For the modest polygon sizes this problem is usually posed with, that is quick. The cost rule here is the polygon form of matrix chain ordering, and research algorithms (Hu and Shing's is the known one) do beat cubic time, but nobody expects them on a whiteboard. Mention them only if asked.
Edge cases
- Exactly three corners: one triangle and no choice, so the answer is the product of the three values.
- Fewer than three values: not a polygon. Return 0 or raise, whichever you agreed with the interviewer, and make sure the code does not index into an empty table.
- All corners equal: every triangulation scores (n - 2) · v³, which makes a quick sanity test.
- Several corners sharing the minimum value: the answer is still unique, but greedy guesses become ambiguous.
- Large values: products of three numbers grow fast. Python integers will not overflow; in Java or C++ check whether a 64-bit type is needed for your bounds.
Common mistakes
- Greedy on the smallest corner. Fanning every diagonal out of the minimum value is often optimal and sometimes not. [9, 7, 8, 6, 7] is a counterexample: the fan from 6 costs 1092 while the best is 1071.
- Filling the table row by row from the top. cost[0][4] needs cost[2][4], which a top-to-bottom row order has not computed yet. Loop on gap length, or run i downward and j upward.
- Letting k equal i or j. The third corner must sit strictly between the chord's endpoints, otherwise you multiply a degenerate triangle.
- Treating it as circular DP. The polygon is a cycle, but fixing the side (0, n - 1) removes the wraparound. No modular indexing is needed.
How the explanation can sound
Fictional example
- Candidate
- Since the polygon is convex, any diagonal is allowed, so this is really about grouping the list. The side between the first and last corner sits in exactly one triangle.
- Candidate
- If I pick that triangle's third corner k, the rest splits into corners 0..k and k..n-1, which I can solve separately. So my state is a pair of indexes, cost(i, j).
- Candidate
- Pairs that are adjacent cost zero. I fill by increasing gap so both halves are ready, try every k in between, and the answer is cost(0, n-1). That is cubic time and quadratic memory.
Other walkthroughs in this set
Strange Printer uses the same kind of interval table but with a twist: a split point only helps when two characters match. Best Time to Buy and Sell Stock with Transaction Fee is a gentler DP with just two states per day, a good contrast when you are revising. For a wider review of the patterns, see algorithm interview questions.
Practicing with Natively
When you drill interval DP on your own, Natively can capture a screenshot of the problem statement, read it, and sketch a recurrence and code in its overlay, which is handy for checking your table order after you have written yours. It can also transcribe a mock interview on your computer, so you can reread whether you explained the fixed side and the split before you started typing. See how an AI interview assistant fits into that routine on Mac and Windows.
Questions people ask
How do you solve Minimum Score Triangulation of Polygon?
Use interval dynamic programming. cost(i, j) is the cheapest way to triangulate corners i through j; try every third corner k between them and take cost(i, k) + cost(k, j) + v[i]·v[k]·v[j]. The answer is cost(0, n - 1).
What is the time complexity of the polygon triangulation DP?
O(n³) time and O(n²) space: there are about n²/2 pairs of corners and each one tries up to n split points.
Why can you fix the side between the first and last corner?
Every triangulation contains exactly one triangle on that side. Choosing its third corner splits the polygon into two smaller convex polygons that can be solved independently, which is what makes the recurrence work.
Does always fanning out from the smallest corner give the answer?
No. It is often optimal but not always. For corner values [9, 7, 8, 6, 7], fanning from the 6 costs 1092 while the best triangulation costs 1071, so you need the full DP.
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.
