Problem 120

Abstract / Summary

Given a triangle of numbers, find the minimum path sum from the top to the bottom by moving to adjacent numbers on the next row.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0120.cpp

class Solution {
    map<pair<int,int>, int> cache;
    int dp(const vector<vector<int>>& tri, int r, int c)
    {
        if (r == tri.size())
            return 0;

        auto lookup = cache.find({r,c});
        if (lookup != cache.end())
            return lookup->second;

        int a = tri[r][c] + dp(tri, r+1, c);
        int b = tri[r][c] + dp(tri, r+1, c+1);
        int result = a < b ? a : b;
        cache[{r,c}] = result;
        return result;
    }

public:
    int minimumTotal(vector<vector<int>>& triangle) {
        cache.clear();
        return dp(triangle, 0,0);
    }
};
24 lines | 620 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The presented implementation solves the classic “minimum path sum in a triangle” problem. It employs a depth-first recursion that explores the two possible moves from each element-downward and down-right-while caching intermediate results to avoid redundant work. The public interface clears any prior state and initiates the recursive process from the apex of the triangle.

Core Logic

The heart of the solution resides in the private dp method. It receives the triangle, a row index r, and a column index c. The first conditional checks whether the recursion has stepped past the last row; reaching this condition signals that no further contribution to the path sum is possible, so the method returns 0.

int dp(const vector<vector<int>>& tri, int r, int c)
{
    if (r == tri.size())
        return 0;

Next, the method attempts to retrieve a previously computed value from the cache. The cache key is a pair<int,int> representing the current coordinates. If the key exists, the stored result is returned immediately, bypassing further recursion.

    auto lookup = cache.find({r,c});
    if (lookup != cache.end())
        return lookup->second;

When a cache miss occurs, the algorithm proceeds to evaluate the two permissible moves. The value at the current cell tri[r][c] is added to the result of recursing to the element directly below (r+1, c) and to the element down-right (r+1, c+1). The smaller of the two sums is selected as the optimal continuation from the current position.

    int a = tri[r][c] + dp(tri, r+1, c);
    int b = tri[r][c] + dp(tri, r+1, c+1);
    int result = a < b ? a : b;

Finally, the computed result is stored in the cache under the current coordinate pair, ensuring that any future request for the same sub-problem can be satisfied instantly. The method then returns the cached value.

    cache[{r,c}] = result;
    return result;
}

Entry Point

The public minimumTotal method prepares the environment for a fresh computation. It clears the cache to guarantee that no stale entries from a previous invocation interfere with the current run. Afterwards, it launches the recursive exploration from the top of the triangle (row 0, column 0) and returns the final minimum path sum.

int minimumTotal(vector<vector<int>>& triangle) {
    cache.clear();
    return dp(triangle, 0,0);
}

Edge Cases Handled

The base-case condition if (r == tri.size()) return 0; gracefully handles the scenario where recursion reaches beyond the bottom row, effectively terminating the path. This also covers the situation of an empty triangle: the initial call to dp receives r == 0 and tri.size() == 0, causing an immediate return of 0.

Because the algorithm always accesses tri[r][c] and tri[r][c+1] only when r is strictly less than tri.size(), it never indexes out of bounds. The triangular structure guarantees that each row r contains exactly r+1 elements, making both c and c+1 valid indices for the recursive calls.

The implementation also works correctly when triangle entries are negative, zero, or positive, as the comparison a < b ? a : b selects the numerically smaller sum without any assumptions about sign.

Performance Optimizations

Memoization is the primary optimization technique employed. By storing each sub-problem result in a map<pair<int,int>, int>, the algorithm eliminates the exponential blow-up typical of naïve recursive solutions. Each distinct coordinate pair is evaluated at most once, turning the overall work into a linear scan over the triangle’s cells.

The explicit cache.clear() at the start of minimumTotal ensures that the map does not retain entries across multiple calls, preventing unnecessary memory growth and guaranteeing that each invocation works with a clean slate.

Using a map provides logarithmic-time lookup and insertion, which is sufficient for the problem size and keeps the implementation straightforward. The early return on the base case prevents deeper recursion once the bottom of the triangle is reached, reducing call-stack depth and associated overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a giant pyramid made of blocks, and you want to walk from the very top down to the bottom. Each block has a special number inside it, and as you step on a block, you add that number to your collection. The goal is to reach the bottom while keeping the total sum of your numbers as small as possible.

To do this, you stand at the top and look at the path ahead. Every time you are on a block, you have two choices: you can step down to the left or step down to the right. This code acts like a smart helper that remembers the best way to get to the bottom from any block where you have already been.

The map acts like a notebook where the helper writes down the smallest total sum it found for each spot. Before the helper calculates the math for a spot, it checks the notebook to see if it has been there before. If the answer is already written down, it just uses that instead of doing all the hard work again.

When the helper stands on a block, it adds the current block number to the result of exploring both the left path and the right path. It picks the path that gives the smaller total. By using the notebook to remember these results, the helper saves lots of time and finds the shortest way through the pyramid very quickly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.78 | σ = 1.17

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
withaarzoo C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
56 links | 41 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Triangle (LeetCode 120) | Easy tutorial | Bottom-up Top-down dynamic programming | StudyAlgorithms'
Nikhil Lohia 17 mins
Triangle (LeetCode 120) | Easy tutorial | Bottom-up Top-down dynamic programming | StudyAlgorithms
YouTube video 'Leetcode Triangle 120 || Code + Explanation + Examples || Dynamic Programming'
Code with Alisha 16 mins
Leetcode Triangle 120 || Code + Explanation + Examples || Dynamic Programming
YouTube video 'Triangle | Live Coding with Explanation | Leetcode - 120'
Algorithms Made Easy 12 mins
Triangle | Live Coding with Explanation | Leetcode - 120
YouTube video '120. Triangle | LEETCODE DYNAMIC PROGRAMMING | LEETCODE MEDIUM | CODE EXPLAINER'
code Explainer 7 mins
120. Triangle | LEETCODE DYNAMIC PROGRAMMING | LEETCODE MEDIUM | CODE EXPLAINER
YouTube video '[Java] Leetcode 120. Triangle [DP Min/Max Path to Target #1]'
Eric Programming 13 mins
[Java] Leetcode 120. Triangle [DP Min/Max Path to Target #1]
YouTube video 'LEETCODE 120 (JAVASCRIPT) | TRIANGLE | CODING INTERVIEW PREP'
Andy Gala 17 mins
LEETCODE 120 (JAVASCRIPT) | TRIANGLE | CODING INTERVIEW PREP
YouTube video 'Leetcode 120 Triangle | DP 2 Approaches | Bottom UP |Top Down | Live coding session'
Coding Decoded 9 mins
Leetcode 120 Triangle | DP 2 Approaches | Bottom UP |Top Down | Live coding session
YouTube video 'LeetCode 120. Triangle 中文解释 Chinese Version'
happygirlzt 8 mins
LeetCode 120. Triangle 中文解释 Chinese Version
YouTube video '120. Triangle | Leetcode Daily - Python'
Leetcode Daily 5 mins
120. Triangle | Leetcode Daily - Python
YouTube video 'Daily Leetcode #804: Jun 13, 2022 - 120. Triangle'
Programming Live with Larry 11 mins
Daily Leetcode #804: Jun 13, 2022 - 120. Triangle
YouTube video 'Triangle | LeetCode 120 | 3 Approaches Explained with Complete Intuition'
Sanyam IIT Guwahati 19 mins
Triangle | LeetCode 120 | 3 Approaches Explained with Complete Intuition
YouTube video '120. Triangle (Leetcode Medium)'
Programming Live with Larry 14 mins
120. Triangle (Leetcode Medium)
YouTube video 'LeetCode 120. Triangle'
Happy Coding 12 mins
LeetCode 120. Triangle
YouTube video 'DP 7. Important Interview Questions of DP on Grids | 64. Minimum Path Sum | 120. Triangle | Leetcode'
Eye on AI and DSA 30 mins
DP 7. Important Interview Questions of DP on Grids | 64. Minimum Path Sum | 120. Triangle | Leetcode
YouTube video 'Daily Leetcode #386: Apr 21, 2021 - 120. Triangle (Linear Space)'
Programming Live with Larry 17 mins
Daily Leetcode #386: Apr 21, 2021 - 120. Triangle (Linear Space)
YouTube video 'LeetCode 120 Triangle | Dynamic Programming | Easy to Understand'
Code Harmony 27 mins
LeetCode 120 Triangle | Dynamic Programming | Easy to Understand
YouTube video 'Triangle | LeetCode 120 - Python'
impoldev 8 mins
Triangle | LeetCode 120 - Python
YouTube video 'Leetcode 120. Triangle | DP Bottom-Up & Top-Down | Python Solution'
StatLearn Tech 16 mins
Leetcode 120. Triangle | DP Bottom-Up & Top-Down | Python Solution
YouTube video 'LeetCode 120 🔥 Triangle | Daily Challenge | Optimal Java DP Solution + Dry Run'
Study Placement 21 mins
LeetCode 120 🔥 Triangle | Daily Challenge | Optimal Java DP Solution + Dry Run
YouTube video '120. Triangle | And Similar Prerequisites | From my DP Playlist | Leetcode Daily Challenge'
Eye on AI and DSA 30 mins
120. Triangle | And Similar Prerequisites | From my DP Playlist | Leetcode Daily Challenge
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality