InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Triangle

medium Original β†—
Solving tips
  • best(i,j) = triangle[i][j] + min(best(i+1,j), best(i+1,j+1)); fill bottom-up so every cell has both children ready.
  • Bottom-up dodges the edge cases that plague top-down (leftmost/rightmost cells have only one valid parent above).
  • Collapse to a single length-n array seeded from the bottom row, overwriting left-to-right, for O(n) space (meets the follow-up).
  • Values can be negative, so greedy 'always pick the smaller next cell' fails - only the DP is correct. O(n^2) time.

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]] β†’ 3 β€” 1 β†’ 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 you can do is triangle[i][j] plus the cheaper of the two cells you can reach below it. That's a recurrence begging for memoization.
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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.