leetcode 118. Pascal’s Triangle memory usage beats 92.69 % of JavaScript submissions.

Posted on

While doing this leetcode problem I ended up with a nice position in memory usage for this problem

var generate = function(numRows) {
    //base cases
    if(numRows === 0){return []}
    if(numRows === 1){return [[1]]}
    if(numRows === 2){return [[1],[1,1]]}
    const arr = [[1],[1,1]]
    //we start with counter of 2 because we are now on the subarray in postion 2
    //  remember arrays are 0 based
    let counter = 2
    while(counter<numRows){
        let row = [1] //fill out the outter left of the triangle
        let innerCounter = 1 //counter for inner loop
        while(innerCounter <= counter-1){
            //push the sum of the values of left and right parent nodes
            // they are not really nodes, but when you look at the provided image
            //  they can be seen as a kind of node
            row.push(arr[counter-1][innerCounter-1] + arr[counter-1][innerCounter])
            innerCounter++
        }
        row.push(1)  //fill out the outer right of the triangle
        arr.push(row)  //push the subarray onto the main array
        counter++
    }
    return arr
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s