Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would be the time complexity of the pascal triangle algorithm

Tasked with solving the following problem (Pascal Triangle) which looks like this.

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

I've successfully implemented the code(see below) but I'm having a tough time figuring out what the time complexity would be for this solution. The number of operations by list is 1 + 2 + 3 + 4 + .... + n would number of operations reduce to n^2 how does the math work and translate into Big-O notation?

I'm thinking this is similar to the gauss formula n(n+1)/2 so O(n^2) but I could be wrong any help is much appreciated

public class Solution {
    public List<List<Integer>> generate(int numRows) {
        if(numRows < 1) return new ArrayList<List<Integer>>();;
        List<List<Integer>> pyramidVal = new ArrayList<List<Integer>>();

        for(int i = 0; i < numRows; i++){
            List<Integer> tempList = new ArrayList<Integer>();
            tempList.add(1);
            for(int j = 1; j < i; j++){
                tempList.add(pyramidVal.get(i - 1).get(j) + pyramidVal.get(i - 1).get(j -1));
            }
            if(i > 0) tempList.add(1);
            pyramidVal.add(tempList);
        }
        return pyramidVal;
    }
}
like image 1000
Marquis Blount Avatar asked Sep 10 '15 09:09

Marquis Blount


1 Answers

Complexity is O(n^2).

Each calculation of element in your code is done in constant time. ArrayList accesses are constant time operations, as well as insertions, amortized constant time. Source:

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time

Your triangle has 1 + 2 + ... + n elements. This is arithmetic progression that sums to n*(n+1)/2, which is in O(n^2)

like image 111
amit Avatar answered Oct 04 '22 14:10

amit