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 Published 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]   9
A four-row triangle made up for this page. The cheapest route, 3 + 2 + 5 + 2 = 12, is shown in brackets.

Greedy 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)
Every route from the top: correct, but 2^(rows - 1) of them.

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]
O(n²) time over all numbers, O(n) extra memory for the bottom row copy.
#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];
}
C++17. Totals are kept in 64-bit integers so long triangles of large values cannot overflow.

A trace

best after each fold, on the example triangle (printed by the code)
StepRow folded inbest (valid part)Reasoning for the first entry
StartBottom row7, 4, 2, 9The bottom costs are the numbers
11, 8, 55, 10, 71 + min(7, 4) = 5
26, 211, 96 + min(5, 10) = 11
33123 + min(11, 9) = 12
best after each fold, on the example triangle (printed by the code). Scroll sideways on a small screen.

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

n = number of rows, so about n²/2 numbers in total
ApproachTimeExtra memory
Every routeO(2^n)O(n) recursion
Memoized recursionO(n²)O(n²) cache
Bottom-up fold (above)O(n²)O(n)
Fold into the input itselfO(n²)O(1), but changes the caller's data
n = number of rows, so about n²/2 numbers in total. Scroll sideways on a small screen.

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

Choosing a direction for the DP
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.

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.

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