Triangle - Problem
Triangle Path Sum Challenge

Imagine you're standing at the top of a mountain represented as a triangular array of numbers. Your goal is to find the minimum cost path from the summit to the base.

๐ŸŽฏ The Rules:
โ€ข Start at the top of the triangle (index 0)
โ€ข At each step, you can only move to adjacent positions in the row below
โ€ข From position i, you can move to either position i or i + 1 in the next row
โ€ข Find the path with the minimum sum of all numbers encountered

Example: Given triangle [[2],[3,4],[6,5,7],[4,1,8,3]], the minimum path is 2 โ†’ 3 โ†’ 5 โ†’ 1 = 11

Input & Output

example_1.py โ€” Basic Triangle
$ Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
โ€บ Output: 11
๐Ÿ’ก Note: The minimum path is 2 โ†’ 3 โ†’ 5 โ†’ 1 with sum = 11. At each level, we choose the adjacent position that leads to the minimum total.
example_2.py โ€” Single Element
$ Input: triangle = [[-10]]
โ€บ Output: -10
๐Ÿ’ก Note: With only one element, the minimum (and only) path sum is the element itself: -10.
example_3.py โ€” Two Rows
$ Input: triangle = [[1],[2,3]]
โ€บ Output: 3
๐Ÿ’ก Note: Two possible paths: 1โ†’2 (sum=3) and 1โ†’3 (sum=4). The minimum is 3.

Constraints

  • 1 โ‰ค triangle.length โ‰ค 200
  • -104 โ‰ค triangle[i][j] โ‰ค 104
  • Triangle property: triangle[i] has exactly i+1 elements

Visualization

Tap to expand
11SUMMIT91076104183๐Ÿ”๏ธ Optimal Path: 2 + 3 + 5 + 1 = 11Green path shows minimum energy descent
Understanding the Visualization
1
Survey the Base
Start at the bottom row - these are our base cases with known costs
2
Work Upward
For each position, choose the minimum cost path from the two adjacent positions below
3
Optimal Substructure
Each position now stores the minimum cost to reach the bottom from that point
4
Reach the Summit
The top position contains the minimum total path cost
Key Takeaway
๐ŸŽฏ Key Insight: Bottom-up DP ensures we always make optimal local decisions that lead to the global optimum!
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
67.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen