Triangle minimum path sum explained
Triangle asks for the smallest sum on a path from the top of a number triangle to its bottom row, where each step goes to one of the two numbers directly below. Work from the bottom up: start with the last row as the best costs, and replace each number in the row above with itself plus the smaller of its two children. After folding every row, the single remaining value is the answer, in O(n²) time for n rows and O(n) extra memory.
By Evin JohnPublished 6 min read
The problem, restated
Row r of the triangle has r + 1 numbers. You start at the single number on top. From position i in one row you may step to position i or i + 1 in the next row. Add up the numbers you visit; return the smallest possible total for a route that ends anywhere in the bottom row.
[3]
6 [2]
1 8 [5]
7 4 [2] 9Greedy fails here. From 3, the cheaper child is 2; from 2, the cheaper child is 5 (8 is the other option); from 5, the cheaper child is 2. That happens to win this time. Now change the bottom 2 to 100: greedy still walks 3, 2, 5 and must finish on 9, for 19, while the route 3, 6, 1, 4 costs 14. Greedy cannot see the expensive bottom row from the top. Interviewers like to hear you rule greedy out with a small counterexample.
Brute force
def min_path_brute(tri):
"""Try every route from the top: 2^(rows - 1) of them."""
def go(r, i):
if r == len(tri) - 1:
return tri[r][i]
return tri[r][i] + min(go(r + 1, i), go(r + 1, i + 1))
return go(0, 0)The repeated work is easy to see: the number in the middle of row 2 is reached from two different parents, and the whole subtree below it is solved twice. Rows deeper down are solved exponentially many times. Caching go(r, i) fixes that, but the bottom-up version is shorter and avoids recursion entirely.
Bottom-up fold
Define best[i] as the cheapest cost from position i in the current row down to the bottom. For the last row, that is just the numbers themselves. For any row above, the cheapest cost from position i is its own value plus the cheaper of the two positions below it. Folding upward row by row overwrites best in place, because position i only reads positions i and i + 1, which have not been overwritten yet in that pass.
def min_path(tri):
"""Bottom-up: start from the last row and fold each row into the one above."""
best = list(tri[-1]) # best cost from each bottom cell
for r in range(len(tri) - 2, -1, -1):
for i in range(r + 1):
best[i] = tri[r][i] + min(best[i], best[i + 1])
return best[0]#include <algorithm>
#include <vector>
long long minPath(const std::vector<std::vector<int>>& tri) {
std::vector<long long> best(tri.back().begin(), tri.back().end());
for (int r = static_cast<int>(tri.size()) - 2; r >= 0; --r) {
for (int i = 0; i <= r; ++i) {
best[i] = tri[r][i] + std::min(best[i], best[i + 1]);
}
}
return best[0];
}A trace
| Step | Row folded in | best (valid part) | Reasoning for the first entry |
|---|---|---|---|
| Start | Bottom row | 7, 4, 2, 9 | The bottom costs are the numbers |
| 1 | 1, 8, 5 | 5, 10, 7 | 1 + min(7, 4) = 5 |
| 2 | 6, 2 | 11, 9 | 6 + min(5, 10) = 11 |
| 3 | 3 | 12 | 3 + min(11, 9) = 12 |
Why bottom-up beats top-down here
A top-down table works too: the cost to reach position i is its value plus the smaller of the two parents above, i - 1 and i. But the edges have only one parent, so you need special cases for i = 0 and i = r, and at the end you must take the minimum across the whole bottom row. Bottom-up has neither problem: every position has exactly two children, and the answer ends at index 0. When an interviewer asks why you chose a direction, this is the answer.
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Every route | O(2^n) | O(n) recursion |
| Memoized recursion | O(n²) | O(n²) cache |
| Bottom-up fold (above) | O(n²) | O(n) |
| Fold into the input itself | O(n²) | O(1), but changes the caller's data |
Edge cases
- One row: the answer is the single number.
- Negative numbers: allowed; the minimum logic works unchanged, and the answer can be negative.
- Two rows: the top plus the smaller of the two below.
- Many equal values: ties do not matter, any route with the same total is fine.
- Very large values over many rows: use 64-bit totals in fixed-width languages.
Where answers go wrong
- Going greedy from the top and taking the smaller child each time.
- Allowing a step to i - 1 as well; only i and i + 1 are reachable.
- In top-down DP, reading a parent index that does not exist at the row edges.
- Returning best[-1] or the minimum of the wrong row after a bottom-up fold.
- Modifying the input triangle without asking, which can surprise the caller.
How to explain it out loud
Fictional example
- Candidate
- Greedy does not work, because a cheap number near the top can lead into an expensive region. So I want the cheapest cost from each position to the bottom.
- Candidate
- From the bottom that is easy: the last row is its own cost. Each position above costs its value plus the cheaper of its two children. I will fold upward, reusing one array the size of the bottom row.
- Interviewer
- Why not go top-down?
- Candidate
- I could, but positions on the left and right edge have only one parent, so I would need special cases, and then a minimum over the last row. Bottom-up has two children everywhere and the answer ends at index 0.
Same idea, other problems
- Cheapest falling path through a square grid, where each step may go down-left, down or down-right. Same fold, three children.
- Most valuable route from the top, maximizing instead of minimizing. Swap min for max.
- Counting routes through a triangle with forbidden cells. The count version of the same shape.
Related walkthroughs
Unique Paths II counts routes through a grid with the same one-row memory trick. Maximal Square folds three neighbors into each cell instead of two. All walkthroughs are on the coding problems hub.
Working through DP problems with Natively
Choosing the direction of a DP and saying why is the part that sounds weak when you have only ever read solutions. Natively can sit in on a mock round on your Mac or Windows machine and keep a transcript of your explanation, so you can check afterward whether you ruled out greedy before reaching for a table. In practice you can also screenshot a triangle-style prompt and ask it for a counterexample to greedy. The coding interview assistant page explains these features.
Questions people ask
How do you solve the Triangle problem?
Start with the bottom row as the costs. For each row above, replace each value with itself plus the smaller of its two children below. After folding to the top, the single value is the minimum path sum.
Why does greedy fail on Triangle?
Taking the smaller child at each step cannot see expensive values further down, so a locally cheap choice can lead into a costly region.
What is the time and space complexity of Triangle?
O(n²) time for n rows, because every number is visited once, and O(n) extra memory for one row of best costs.
Why go bottom-up instead of top-down?
Bottom-up gives every position exactly two children and ends with the answer at index 0. Top-down needs edge special cases and a minimum over the last row.
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.
