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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

DEV works best when you're signed in—unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay