Triangle (LeetCode 120): Solution and Explanation

Medium
Array
Dynamic Programming

You get a triangle of numbers where row i has i + 1 entries. Starting from the top, each step moves to one of the two adjacent entries in the next row, and you want the smallest possible sum of a path that reaches the bottom row.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Trying every path is the brute force. From each entry there are two choices, so a triangle with n rows has 2 to the n - 1 paths, which explodes for even a few dozen rows. The redundancy is easy to spot: many paths pass through the same entry, and the cheapest way to reach that entry is the same no matter where the path goes next.

So define dp[i][j] as the minimum sum of a path from the top to entry j of row i. An entry can only be reached from directly above (index j in the previous row) or from above and to the left (index j - 1). That gives dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]. The edges of the triangle are special: the first entry of a row can only be reached from the first entry above, and the last entry can only be reached from the last entry above.

Fill the rows top to bottom, and the answer is the minimum value in the last row, since the path may end at any bottom entry. The reference code copies the triangle into dp so the first row is already correct and every later cell starts with its own value, then overwrites each cell with the full path cost.

Approach: Top-down row DP

  1. Copy the triangle into dp, so dp[0][0] is already the cost of reaching the top.
  2. Loop over rows i from 1 to n - 1 and over each index j in that row.
  3. If j == 0, the only parent is dp[i - 1][0], so add that to triangle[i][j].
  4. If j is the last index, the only parent is dp[i - 1][j - 1].
  5. Otherwise take min(dp[i - 1][j - 1], dp[i - 1][j]) and add triangle[i][j].
  6. Return min(dp[n - 1]), the cheapest way to finish in the bottom row.

Step-by-step example

triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
  1. Row 0 stays [2].
  2. Row 1: 3 + 2 = 5 and 4 + 2 = 6, giving [5, 6].
  3. Row 2: the first entry is 6 + 5 = 11, the middle is 5 + min(5, 6) = 10, and the last is 7 + 6 = 13, giving [11, 10, 13].
  4. Row 3: 4 + 11 = 15, then 1 + min(11, 10) = 11, then 8 + min(10, 13) = 18, then 3 + 13 = 16, giving [15, 11, 18, 16].
  5. The minimum of the last row is 11, the path 2, 3, 5, 1.

Code: Python, Java, C++

1class Solution:
2    def minimumTotal(self, triangle: List[List[int]]) -> int:
3        n = len(triangle)
4        dp = [row[:] for row in triangle]
5
6        for i in range(1, n):
7            for j in range(len(triangle[i])):
8                if j == 0:
9                    dp[i][j] = dp[i-1][j] + triangle[i][j]
10                elif j == len(triangle[i]) - 1:
11                    dp[i][j] = dp[i-1][j-1] + triangle[i][j]
12                else:
13                    dp[i][j] = min(dp[i-1][j-1], dp[i-1][j]) + triangle[i][j]
14
15        return min(dp[n-1])

Time and space complexity

Time

O(n²)

With n rows the triangle has about n² / 2 entries, and each is processed once with constant work.

Space

O(n²)

The dp copy stores every entry of the triangle.

Other approaches

Bottom-up with one row (time O(n²), space O(n))

Start from a copy of the last row and move upward, setting row[j] = triangle[i][j] + min(row[j], row[j + 1]). The edges need no special cases because every entry has two children, and the answer ends up in row[0]. This meets the O(n) space follow up.

Memoized recursion (time O(n²), space O(n²))

Recurse from the top with best(i, j) = triangle[i][j] + min(best(i + 1, j), best(i + 1, j + 1)) and cache results. Same idea as the bottom-up version, with recursion overhead.

Common mistakes

  • Greedily picking the smaller of the two children at every step. In this example the greedy path can work, but in general a small step can lead into a region of large numbers.
  • Forgetting the edge cases for the first and last entries of each row, which reads dp[i - 1][-1] in Python (the wrong cell) or goes out of bounds in Java and C++.
  • Returning dp[n - 1][0] or the last element instead of the minimum over the whole bottom row.
  • Assigning dp = triangle without copying, which mutates the input; that may be acceptable but surprises callers.

Frequently asked questions

Top-down or bottom-up for the triangle problem?

Both give the right answer. Bottom-up is a little cleaner because every entry has two children, so there are no edge cases and the answer is a single value at the top.

Can you solve Triangle in O(n) extra space?

Yes. Process from the bottom row upward and keep one array the size of the bottom row, overwriting it as you go.

Why doesn't a greedy approach work?

Choosing the smaller neighbor at each step ignores what comes later. A path that starts with a slightly larger number can avoid much larger numbers further down.

What is the time complexity?

O(n²) for n rows, because the triangle has roughly n² / 2 entries and each is visited once.