InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Triangle

medium Original ↗ 00:00

Problem

You’re given a triangle as a list of rows, where row i has i + 1 numbers. Starting at the single top element, walk down to the bottom row, adding the numbers you step on. From position j in a row you may step to position j or j + 1 in the row below (the two entries directly beneath). Return the minimum possible path sum from top to bottom.

Examples

  • triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]11 — path 2 → 3 → 5 → 1.
  • triangle = [[-10]]-10 — a single element is the whole path.
  • triangle = [[1],[2,3]]31 → 2; choosing 3 would give 4.

Constraints

  • 1 <= triangle.length <= 200
  • triangle[i].length == i + 1
  • -10⁴ <= triangle[i][j] <= 10⁴
  • Follow-up: solve using only O(n) extra space, where n is the number of rows.

Think about it first

Hint 1 From cell (i, j), the best result is triangle[i][j] plus the cheaper of the two cells reachable below it. This recurrence has overlapping subproblems, so it can be memoized.
Hint 2 best(i, j) = triangle[i][j] + min(best(i+1, j), best(i+1, j+1)), with the bottom row as the base case. The answer is best(0, 0).
Hint 3 Fill it bottom-up: start from the last row and collapse upward. Each cell overwrites into a single 1-D array of length n, since row i needs only the already-computed row i+1.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug