Skip to main content

120. Triangle

medium

Given a triangle of values, find the minimum top-to-bottom path sum where each step goes to an adjacent cell on the next row. Bottom-up DP collapses to O(n) space.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a triangle array, return the minimum path sum from top to bottom. For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.

Constraints

  • 1 <= triangle.length <= 200
  • triangle[0].length == 1
  • triangle[i].length == triangle[i - 1].length + 1
  • -10^4 <= triangle[i][j] <= 10^4

Examples

Example 1

Input
triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output
11

Explanation: 2 + 3 + 5 + 1 = 11 is the minimum path.

Example 2

Input
triangle = [[-10]]
Output
-10

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Top-down DP: dp[i][j] = min path sum reaching (i, j). Two parents: (i-1, j-1) and (i-1, j) (with boundary cases).

Hint 2

Bottom-up is cleaner: start from the last row and roll upward. dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).

Hint 3

Final answer sits at dp[0]. O(n) extra space.

Solution approach

Reveal approach

Bottom-up DP collapses to a 1D rolling array. Define the subproblem dp[j] at row i = the minimum path sum from cell (i, j) down to the last row. The recurrence relation is dp[j] = triangle[i][j] + min(dp[j], dp[j+1]) when scanning rows from bottom to top — from cell (i, j) you can step into (i+1, j) or (i+1, j+1). Base case: initialize dp as a copy of the last row. Iterate i from n-2 down to 0, updating dp[j] for j in 0..i (in place is safe because each dp[j] reads the row-below dp[j] and dp[j+1]). Return dp[0]. Time O(n^2) where n is the number of rows; extra space O(n). Top-down is symmetric but requires boundary handling on the diagonal edges.

Complexity

Time
O(n^2)
Space
O(n)

Related patterns

  • dynamic-programming
  • memoization-recursion

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Bloomberg

Practice these live with InterviewChamp.AI

Drill Triangle and Dynamic Programming problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →