DEV Community

Irina
Irina

Posted on

Leetcode 118. Pascal's Triangle

Hello Dev Community,
I'm posting my solution to the Leetcode problem #118. Pascal's Triangle Easy

Description:

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Pascal's triangle

var generate = function(numRows) {
    let res = []

    for (let i = 0; i < numRows; i++) {
        let arr = new Array(i+1)
        arr[0] = arr[arr.length - 1] = 1

        for (let j = 1; j < arr.length-1; j++) {
            arr[j] = res[i-1][j-1] + res[i-1][j]
        }

        res.push(arr)
    }

    return res
};

console.log(generate(5));
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Enter fullscreen mode Exit fullscreen mode

Method - Nested loops
Complexity - Time O(n^2) | Space O(n^2). Basically complexity here is the product of height and width of the triangle i * j, which simplifies to n^2.

I welcome your comments or suggestions!

Top comments (0)