Taro Logo

Triangle

#139 Most AskedMedium
0 views
Topics:
Dynamic Programming

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.

Example 1:

Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Explanation: The triangle looks like:
   2
  3 4
 6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).

Example 2:

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

Constraints:

  • 1 <= triangle.length <= 200
  • triangle[0].length == 1
  • triangle[i].length == triangle[i - 1].length + 1
  • -104 <= triangle[i][j] <= 104
Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the triangle contain negative numbers, or are all values guaranteed to be non-negative integers?
  2. What should be returned if the input triangle is empty or null?
  3. Can I modify the input triangle in-place to optimize space complexity, or do I need to keep the original data intact?
  4. Is the triangle guaranteed to be valid (i.e., every row $i$ has exactly $i + 1$ elements)?
  5. Are the values in the triangle constrained to fit within standard integer limits, or could we face overflow issues with the path sums?

Brute Force Solution

Approach

Imagine standing at the top of a pyramid of numbers and trying to find a path down to the bottom that adds up to the smallest possible total. The brute force approach works by exploring every single possible pathway from the top to the bottom.

Here's how the algorithm would work step-by-step:

  1. Start at the topmost number.
  2. From your current position, look at the two numbers directly below you and choose one to step to.
  3. Continue making choices downward until you reach the very bottom of the pyramid.
  4. Add up all the numbers you stepped on along that specific path to get a total sum.
  5. Go back to the top and repeat the entire journey, making a different sequence of left and right choices, to find a new path.
  6. Do this for every single possible combination of steps from the top to the bottom.
  7. Compare the totals of every completed path and pick the smallest one as your final answer.

Code Implementation

def minimum_total_brute_force(triangle_grid):
    
    # Explore all possible paths recursively to evaluate every unique route to the bottom
    def explore_paths(row_index, element_index):
        if row_index == len(triangle_grid):
            return 0
            
        current_value = triangle_grid[row_index][element_index]
        
        left_path_sum = explore_paths(row_index + 1, element_index)
        
        right_path_sum = explore_paths(row_index + 1, element_index + 1)
        
        # Choose the path yielding the smaller sum to bubble up the optimal local decision
        return current_value + min(left_path_sum, right_path_sum)

    # Initiate the exhaustive search starting from the very top peak of the triangle
    return explore_paths(0, 0)

Big(O) Analysis

Time Complexity
–
Space Complexity
O(N) – To find the minimum path sum without modifying the input, we allocate an auxiliary one-dimensional array of size N, where N represents the number of rows in the triangle, to store intermediate totals as we move upward from the bottom. This auxiliary array requires extra memory proportional to the height of the triangle. As the number of rows N increases, the space used by this temporary row tracking grows linearly. Therefore, the overall auxiliary space complexity simplifies to O(N).

Optimal Solution

Approach

Instead of trying to figure out the best path by starting at the very top and guessing blindly, the smartest strategy works backward from the very bottom. By looking at the last row first and making cheap local choices as you move upward, you naturally uncover the best overall path without having to check every single combination.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the numbers in the bottom-most row of the structure.
  2. Move up to the row immediately above the bottom. For each number in this row, look directly below it and to its immediate diagonal neighbor.
  3. Add your current number to whichever of those two choices below is smaller, and keep that sum as your new value.
  4. Repeat this exact same addition process for every number in the current row, always picking the smaller path underneath you.
  5. Step up to the next row and repeat the same addition process, using the updated totals from the row you just finished calculating.
  6. Continue moving upward row by row, always rolling the best choices from the bottom into the numbers above.
  7. Once you finally reach the single starting number at the very top, the accumulated value sitting there will magically represent the lowest possible sum of the entire journey.

Code Implementation

def minimum_total(triangle_matrix):
    # Working bottom-up avoids redundant path calculations and exponential time complexity.
    for row_index in range(len(triangle_matrix) - 2, -1, -1):
        
        for element_index in range(len(triangle_matrix[row_index])):
            # Choosing the smaller local option ensures the global sum remains optimal.
            triangle_matrix[row_index][element_index] += min(
                triangle_matrix[row_index + 1][element_index],
                triangle_matrix[row_index + 1][element_index + 1]
            )
            
    # The top element accumulates the absolute minimum path sum from the entire traversal.
    return triangle_matrix[0][0]

Big(O) Analysis

Time Complexity
O(n²) – To analyze the time complexity, let n represent the total number of rows in the triangle. The outer loop iterates upward through the rows starting from the second-to-last row down to the top, which takes roughly n steps. Inside this outer loop, an inner loop iterates horizontally across each element in the current row, checking the two adjacent values directly below it. Since the number of elements in each row increases linearly from 1 up to n, the total number of additions performed across all rows roughly approximates the sum of an arithmetic series like n * (n - 1) / 2. As we drop constant factors and lower-order terms, this total number of operations simplifies to a Big O time complexity of O(n²).
Space Complexity
O(1) – The algorithm modifies the input triangle in place from the bottom up without allocating any new auxiliary data structures. A few scalar variables are used to track loop indices, resulting in a constant amount of extra memory regardless of the input size. Since N represents the number of rows in the triangle, the auxiliary space complexity remains independent of N.

Edge Cases

Empty triangle or null input
How to Handle:
Return zero immediately as the minimum path sum for an empty structure is undefined or zero.
Triangle with only a single row containing one element
How to Handle:
Return that single element directly without performing any additional row transitions.
Triangle containing negative numbers
How to Handle:
Ensure the dynamic programming recurrence relation correctly accumulates negative values to yield a smaller path sum.
Asymmetric or ragged triangular structures
How to Handle:
Validate that each row length strictly equals its row index plus one to prevent out-of-bounds indexing.
Very large triangle heights approaching maximum constraints
How to Handle:
Use bottom-up dynamic programming with O(n) space optimization to prevent stack overflow and memory limit issues.
All elements in the triangle are identical
How to Handle:
The algorithm correctly computes the cumulative path by continuously adding the node value to the minimum of its children.
Extreme boundary elements on the far left or right edges
How to Handle:
Handle boundary conditions explicitly by only considering a single adjacent child rather than two.
Very large positive numbers causing potential integer overflow
How to Handle:
Ensure the data types used for accumulation can hold values exceeding standard 32-bit integer limits if inputs are large.
0/257 completed