Browse curriculum

Triangle (LeetCode 120)

Triangle (LeetCode 120): find the minimum path sum from the top of a triangle to the bottom with bottom-up DP: each cell adds the cheaper of its two children.

Problem Understanding

Triangle: given a triangle array, return the minimum path sum from top to bottom. From index j in one row you may move to index j or j + 1 in the next row.

Example: [[2],[3,4],[6,5,7],[4,1,8,3]] returns 11: 2 + 3 + 5 + 1.

The Intuition: Let the Bottom Decide

The cheapest path from any cell depends only on the cells below it. So work upward:

  1. The bottom row needs no work: each value is the best path from that cell.
  2. A cell one row up chooses the cheaper of its two children: best[i][j] = triangle[i][j] + min(best[i+1][j], best[i+1][j+1]).
  3. Repeat to the top. The top cell holds the answer.

This is the same "value plus the cheaper neighbour" rule as Minimum Path Sum, on a triangle instead of a grid, and the same shape as Pascal's Triangle, with min instead of +. One array of the bottom row's length is all the dynamic programming needs.

Triangle Visualization

NUMBER UNDER A CELL = CHEAPEST SUM FROM IT TO THE BOTTOM

BOTTOM ROW AS IT IS

2

·

3

·

4

·

6

·

5

·

7

·

4

4

1

1

8

8

3

3

cell best

:

answer

:

 

Start with the bottom row as it is: [4, 1, 8, 3]. Each value is the best path from that cell

Next

(2, 0) = 6: children's bests are 4 and 1. 6 + 1 = 7

Free preview: the first 3 of 8 steps

triangle

Under each cell is its best sum to the bottom, filled from the bottom row up. The cell being computed is solid and the cheaper child it used is tinted; the minimum path turns green at the end. Try Greedy trap to see why taking the cheaper step every time fails.

Triangle Dry Run

Input: [[2],[3,4],[6,5,7],[4,1,8,3]]. dp starts as the bottom row [4, 1, 8, 3].

Row Cell Calculation dp after
2 6 6 + min(4, 1) = 7 [7, 1, 8, 3]
2 5 5 + min(1, 8) = 6 [7, 6, 8, 3]
2 7 7 + min(8, 3) = 10 [7, 6, 10, 3]
1 3 3 + min(7, 6) = 9 [9, 6, 10, 3]
1 4 4 + min(6, 10) = 10 [9, 10, 10, 3]
0 2 2 + min(9, 10) = 11 [11, 10, 10, 3]

Answer: dp[0] = 11.

Triangle LeetCode Solution

One array of the bottom row's length, overwritten from left to right in each row going up.

Triangle Code
1var minimumTotal = function(triangle) {
2 const dp = [...triangle[triangle.length - 1]];
3 for (let i = triangle.length - 2; i >= 0; i--) {
4 for (let j = 0; j <= i; j++) {
5 dp[j] = triangle[i][j] + Math.min(dp[j], dp[j + 1]);
6 }
7 }
8 return dp[0];
9};

Triangle in Python, Java, C++, TypeScript and C

Triangle in Python
class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        dp = triangle[-1][:]
        for i in range(len(triangle) - 2, -1, -1):
            for j in range(i + 1):
                dp[j] = triangle[i][j] + min(dp[j], dp[j + 1])
        return dp[0]
Triangle in Java
class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        int n = triangle.size();
        int[] dp = new int[n];
        for (int j = 0; j < n; j++) dp[j] = triangle.get(n - 1).get(j);
        for (int i = n - 2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                dp[j] = triangle.get(i).get(j) + Math.min(dp[j], dp[j + 1]);
            }
        }
        return dp[0];
    }
}
Triangle in C++
class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        vector<int> dp = triangle.back();
        for (int i = (int)triangle.size() - 2; i >= 0; i--) {
            for (int j = 0; j <= i; j++) {
                dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
            }
        }
        return dp[0];
    }
};
Triangle in TypeScript
function minimumTotal(triangle: number[][]): number {
    const dp = [...triangle[triangle.length - 1]];
    for (let i = triangle.length - 2; i >= 0; i--) {
        for (let j = 0; j <= i; j++) {
            dp[j] = triangle[i][j] + Math.min(dp[j], dp[j + 1]);
        }
    }
    return dp[0];
}
Triangle in C
int minimumTotal(int** triangle, int triangleSize, int* triangleColSize) {
    int n = triangleSize;
    int* dp = malloc(n * sizeof(int));
    for (int j = 0; j < n; j++) dp[j] = triangle[n - 1][j];
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j <= i; j++) {
            int a = dp[j], b = dp[j + 1];
            dp[j] = triangle[i][j] + (a < b ? a : b);
        }
    }
    int ans = dp[0];
    free(dp);
    return ans;
}

Edge Cases & Common Mistakes

  • One row: the answer is that single value.
  • Greedy steps: picking the cheaper child at each level can lead into expensive rows; compare whole sums.
  • Top-down without care: the edge cells of each row have only one parent; bottom-up avoids those special cases.
  • 1-D update order: going left to right is safe because dp[j + 1] is overwritten after dp[j] reads it.
  • Negative numbers: fine; the recurrence never assumes values are positive.

Summary

Copy the bottom row into dp, then for each row going up set dp[j] = triangle[i][j] + min(dp[j], dp[j+1]). Return dp[0]. O(n²) time over the n(n+1)/2 cells and O(n) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start from the bottom row

    dp = a copy of the last row: each value is already the best path from that cell.

  2. Move up one row at a time

    For each row i from n - 2 down to 0 and each j from 0 to i: dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]).

  3. Read the top

    dp[0] is the minimum path sum.

Frequently asked questions

Why solve Triangle bottom-up instead of top-down?

From the top, each cell can be reached from one or two parents, and the bottom row has n candidate endpoints to compare at the end. From the bottom, every cell has exactly two children and the answer lands in a single cell, the top. The recurrence is simply best[i][j] = triangle[i][j] + min(best[i+1][j], best[i+1][j+1]).


How does the O(n) space version work?

Keep one array dp initialised to the bottom row. For each row from the second-to-last up, overwrite dp[j] with triangle[i][j] + min(dp[j], dp[j+1]), with j running left to right. dp[j+1] still holds the row below, because it is only overwritten after dp[j].


Why doesn't a greedy choice work?

Choosing the cheaper next cell at each step ignores what lies below it. In [[1],[2,3],[9,9,1],[9,9,9,1]] greedy goes 1, 2, 9, 9 for 21, while the best path is 1, 3, 1, 1 for 6.


Can you modify the input triangle in-place for O(1) auxiliary space?

Yes. Starting from the second-to-last row up to the top, triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) overwrites the array in place, requiring O(1) extra space without allocating a separate DP array.


What is the time complexity of the Triangle problem?

The time complexity is O(n^2) where n is the number of rows in the triangle. A triangle with n rows contains n(n + 1)/2 total cells, and every cell is evaluated once.

New to the technique behind this problem? Watch it run step by step:

Dynamic Programming Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description