LeetCode – Triangle (Java)

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

Bottom-Up (Good Solution)

We can actually start from the bottom of the triangle.

public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
	int[] total = new int[triangle.size()];
	int l = triangle.size() - 1;
 
	for (int i = 0; i < triangle.get(l).size(); i++) {
		total[i] = triangle.get(l).get(i);
	}
 
	// iterate from last second row
	for (int i = triangle.size() - 2; i >= 0; i--) {
		for (int j = 0; j < triangle.get(i + 1).size() - 1; j++) {
			total[j] = triangle.get(i).get(j) + Math.min(total[j], total[j + 1]);
		}
	}
 
	return total[0];
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Rudolf Eremyan

    Without using Extra Space, just modified existing ArrayLists

    public static int findMinPath(ArrayList<ArrayList> lists) {

    if(lists.size() == 1){
    return lists.get(0).get(0);
    }

    for(int i = lists.size()-2; i >= 0; i–){
    int size = lists.get(i).size();

    for(int j = 0; j < size; j++){
    int min = Math.min( (lists.get(i).get(j) + lists.get(i+1).get(j)), (lists.get(i).get(j) + lists.get(i+1).get(j+1)) );
    lists.get(i).set(j, min);
    }
    }

    return lists.get(0).get(0);
    }

  • Surabhi Dixit

    Anything wrong with my solution?

    public static int addinput(int[][]x)
    {
    int i=0,j=0,sum=0,previous=0;
    while(i1&&j!=1)
    j=1;

    }
    return sum;
    }

  • Piyush Chaudhary

    Wrong solution. Won’t work for : [[-1],[2,3],[1,-1,-3]]

  • kUkaraCH4

    This solution uses O(n) extra space. You can technically use O(1) space, given that modification of the original triangle is allowed, by storing the partial minimum sum of the current value and the smaller of its lower neighbors. If we need to restore the original triangle we can then do it in a separate method which does use O(n) extra space but is only called lazily when needed:

    public int minimumTotal(ArrayList<ArrayList> a) {
    if (a == null || a.size() == 0) return -1;
    if (a.size() == 1) return a.get(0).get(0);
    for (int i = a.size() - 2; i >= 0; i--) {
    ArrayList low = a.get(i);
    ArrayList high = a.get(i+1);
    for (int j = 0; j i).toArray();
    for (int i = a.size() - 2; i >= 0; i--) {
    ArrayList curr = a.get(i);
    for (int j = 0; j < curr.size(); j++) {
    int sum = curr.get(j);
    curr.set(j, curr.get(j) - Math.min(mem[j], mem[j+1]));
    mem[j] = sum;
    }
    }
    return res;
    }

  • Candis

    The first solution could have been right had we created another array and stored there and then copied it back to temp.! The space was still O(N)! 🙂

  • lthuongvn

    Can we solve this problem by finding the minimum value at each row. Then the path from top to bottom would be the root, min of 1st row, min of 2nd row,,., min of last row.

  • up23

    In php or any language using a min() function, it’s simple:

    function minTotal( array $rows) {
    $bestAns = 0;

    for ($i = 0; $i < count($rows); $i ++) {
    $bestAns += min($rows[$i]);
    }

    return $bestAns;
    }

  • Adil qureshi

    /** Very Easy & Working.

    Class Solution {
    public int doSum(ArrayList<ArrayList> inputList) {
    int sum = 0;

    for (ArrayList list : inputList) {
    int minimun = Integer.MAX_VALUE;
    for (Integer num : list) {
    int tempMin = Math.min(num, minimun);
    minimun = tempMin;
    }
    sum = sum + minimun;

    }

    return sum;
    }
    }

  • Sureshkumar T

    Thanks for pointing the mistake probably i have overlooked the question. Here is the solution with complexity of O(n)

    public static int minimumAdjacentTotal(List<List> triangle) {
    if (triangle.size() <= 0) {
    return 0;
    } else {
    int sum = 0;
    int pos = 0;
    for (List row : triangle) {
    if(row.size()>1) {
    if(row.get(pos) < row.get(pos + 1)) {
    sum += row.get(pos);
    } else {
    sum += row.get(pos+1);
    pos++;
    }
    } else {
    sum += row.get(pos);
    }
    }
    return sum;
    }
    }

  • iberras

    This doesn’t work with the adjacent condition. It’s a smart move, but if you order he items, then you could pick one that is not adjacent…

  • Sureshkumar T

    We can use a treeSet to store the elements of each row so we can solve the problem with complexity of O(n).

  • Lucy

    Hi,

    I think second line of second solution is not right. You use total to record every path’s cost in one layer right?

    So the first two lines should be:

    int l = triangle.size() – 1;

    int[] total = new int[triangle.get(l).size()];

  • df

    python solution

    def min_path_sum(arr):

    min_sum = 0
    for i in range(len(arr)):
    print (‘+’ ,min(arr[i]))
    min_sum += min(arr[i])
    return min_sum

  • Jie

    public class Solution {

    public int minimumTotal(ArrayList<ArrayList> triangle) {

    int height = triangle.size();

    for (int i=height-2; i>=0; i–){

    for (int j=0; j<i+1; j++){

    ArrayList current = triangle.get(i);

    ArrayList next = triangle.get(i+1);

    current.set(j, current.get(j) + Math.min(next.get(j), next.get(j+1)));

    }

    }

    return triangle.get(0).get(0);

    }

    }

    you can make space to O(1)