#120

Triangle

Medium
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(n)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution uses dynamic programming to build the minimum path sum from the bottom of the triangle to the top. By modifying the triangle in place, we can keep track of the minimum sums without using extra space, achieving an efficient solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Start from the second last row of the triangle and move upwards.
  2. 2Step 2: For each element, update it to be the sum of itself and the minimum of the two adjacent elements in the row below.
  3. 3Step 3: The top element will contain the minimum path sum after processing all rows.
solution.py5 lines
1def minimumTotal(triangle):
2    for row in range(len(triangle) - 2, -1, -1):
3        for col in range(len(triangle[row])):
4            triangle[row][col] += min(triangle[row + 1][col], triangle[row + 1][col + 1])
5    return triangle[0][0]

Complexity note: The time complexity remains O(n²) as we still visit each element, but the space complexity is O(1) since we modify the triangle in place.

  • 1Dynamic programming allows us to build solutions incrementally.
  • 2In-place updates can save space and improve efficiency.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.