LeetCode #120 Medium

Triangle

Triangle is LeetCode 120 (Medium). triangle has n rows, and row i holds i + 1 numbers.

  • Start at the single number on top and move down one row at a time.
  • From index j you may step to index j or j + 1 on the row below.
  • Return the smallest possible sum of a path that reaches the bottom row.

Values can be negative. The follow-up asks for only O(n) extra space, where n is the number of rows.

Constraints
  • 1 <= triangle.length <= 200
  • triangle[0].length == 1
  • triangle[i].length == triangle[i - 1].length + 1
  • -10⁴ <= triangle[i][j] <= 10⁴
dynamic-programmingarray
Open on LeetCode ↗
02

Intuition

Choosing from the top is hard, because a small step now can lead into large numbers later. Choosing from the bottom is easy. A number on the last row has nothing below it, so its best path is just itself.

One row up, each number has exactly two children, and both children already know their best path to the bottom. So its own best is its value plus the smaller of its two children's bests. Repeat row by row, and the top cell ends up holding the answer.

Each row only reads the row directly below it, so a single array of length n is enough.

How to spot this pattern

"Move down to one of two neighbours, minimise the total" is a grid DP where every cell depends on a fixed set of cells below it. Solving from the side with no choices left, here the bottom row, removes all the boundary checks.

03

Approach

Try it first

Before reading on, decide what the best path from a bottom-row cell is, and how one cell can reuse the answers of its two children. Then check whether you need a full 2D table or only one row. Aim for O(n²) time and O(n) space.

1

Copy the bottom row

Set dp to a copy of the last row. dp[j] means the smallest sum from cell j of the current row down to the bottom, and for the last row that is the cell's own value.

2

Fold each row into the one below

For rows r = n - 2 up to 0, and j = 0 to r, set dp[j] = triangle[r][j] + min(dp[j], dp[j + 1]). The two children of cell (r, j) are (r + 1, j) and (r + 1, j + 1), and their bests are still sitting in dp[j] and dp[j + 1].

3

Why left to right is safe

Writing dp[j] overwrites a child value, but only cell j itself ever reads dp[j] again: cell j + 1 reads dp[j + 1] and dp[j + 2]. So no later cell on the row loses a value it needs.

4

Return the top

After row 0 is folded, dp[0] is the best path from the top cell to the bottom, which is the answer. The rest of dp holds stale values from lower rows and is ignored.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minimumTotal(self, triangle):
▶3 dp = triangle[-1][:]
▶4 for r in range(len(triangle) - 2, -1, -1):
▶5 for j in range(r + 1):
▶6 dp[j] = triangle[r][j] + min(dp[j], dp[j + 1])
▶7 return dp[0]
2346574best 41best 18best 83best 3dp row40118233this cellbottom row: each best is its own value
dp4, 1, 8, 3copy of the last row
A number on the bottom row has nothing below it, so its best path to the bottom is just itself. The dp row starts as a copy of that row.
2346best 7574best 41best 18best 83best 3dp row70118233this cell6+1=7value + smaller best belowcell 6: children best 4 and 1 → take 1
row2
dp[0]7
Cell 6 can step down to the cells below it, whose best paths are 4 and 1. Taking the smaller, 1, gives 7. It overwrites slot 0, which only this cell needed; slot 1 is left for the next cell.
2346best 75best 674best 41best 18best 83best 3dp row70618233this cell5+1=6value + smaller best belowcell 5: children best 1 and 8 → take 1
row2
dp[1]6
Cell 5 can step down to the cells below it, whose best paths are 1 and 8. Taking the smaller, 1, gives 6. It overwrites slot 1, which only this cell needed; slot 2 is left for the next cell.
2346best 75best 67best 104best 41best 18best 83best 3dp row706110233this cell7+3=10value + smaller best belowcell 7: children best 8 and 3 → take 3
row2
dp[2]10
Cell 7 can step down to the cells below it, whose best paths are 8 and 3. Taking the smaller, 3, gives 10. It overwrites slot 2, which only this cell needed; slot 3 is left for the next cell.
23best 946best 75best 67best 104best 41best 18best 83best 3dp row906110233this cell3+6=9value + smaller best belowcell 3: children best 7 and 6 → take 6
row1
dp[0]9
Cell 3 can step down to the cells below it, whose best paths are 7 and 6. Taking the smaller, 6, gives 9. It overwrites slot 0, which only this cell needed; slot 1 is left for the next cell.
23best 94best 106best 75best 67best 104best 41best 18best 83best 3dp row9010110233this cell4+6=10value + smaller best belowcell 4: children best 6 and 10 → take 6
row1
dp[1]10
Cell 4 can step down to the cells below it, whose best paths are 6 and 10. Taking the smaller, 6, gives 10. It overwrites slot 1, which only this cell needed; slot 2 is left for the next cell.
2best 113best 94best 106best 75best 67best 104best 41best 18best 83best 3dp row11010110233this cell2+9=11value + smaller best belowcell 2: children best 9 and 10 → take 9
row0
dp[0]11
Cell 2 can step down to the cells below it, whose best paths are 9 and 10. Taking the smaller, 9, gives 11. It overwrites slot 0, which only this cell needed; slot 1 is left for the next cell.
2best 113best 94best 106best 75best 67best 104best 41best 18best 83best 3dp row11010110233this celltop cell best 11 → answer
answer11
The top cell now holds the smallest sum of any path to the bottom: 11.
05

Common pitfalls

Taking the smaller step on the way down

✗ Wrong
j, total = 0, triangle[0][0]
for r in range(1, n):
    if triangle[r][j + 1] < triangle[r][j]:
        j += 1
    total += triangle[r][j]
✓ Right
dp[j] = triangle[r][j] + min(dp[j], dp[j + 1])

A greedy step only sees the next row. On [[1], [2, 3], [9, 9, 1]] it steps to 2 and then must take a 9, for 12, while 1 → 3 → 1 sums to 5.

Reading past the end of a zero-filled row

✗ Wrong
dp = [0] * n
for r in range(n - 1, -1, -1):
    for j in range(r + 1):
        dp[j] = triangle[r][j] + min(dp[j], dp[j + 1])
✓ Right
dp = [0] * (n + 1)
for r in range(n - 1, -1, -1):
    ...

Starting from zeros means the bottom row is folded too, and its last cell reads dp[n]. With length n that index does not exist, so even [[-10]] crashes. Either pad to n + 1 or copy the bottom row and start one row higher.

06

Edge cases

A single row

The loop over rows never runs, so the answer is that one value, even when it is negative: [[-10]] returns -10.

07

Complexity

Time
O(n²)
Space
O(n)
There are n(n + 1) / 2 cells and each is folded once with one comparison; 200 rows is 20,100 cells. The only extra memory is dp, one entry per row.
08

Triangle FAQ

Can I solve it top-down instead?

Yes. Let best[r][j] be the smallest sum from the top down to (r, j); it takes from (r - 1, j - 1) and (r - 1, j), but the first and last cell of each row have only one parent. The answer is then the minimum of the whole last row. Bottom-up avoids both the special cases and the final scan.

Is it fine to write the sums into the triangle itself?

It works and drops the extra memory to O(1): fold each row into triangle[r + 1] and return triangle[0][0]. The catch is that it destroys the input, which a caller may still need, so most interviewers expect you to ask first.