Forming Pascal’s triangle given a number of rows

Kevin W
3 min readNov 11, 2019

--

Photo by Drew Graham on Unsplash

For this week, I encountered a problem on Leetcode that shows a Pascal’s triangle. I knew of the structure how a Pascal’s triangle beforehand as I took many mathematical courses in high school and college so I understood what it would look like for the output.

Pascal’s triangle representation

Problem

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle. The output will be all arrays separated by new lines.

Assumptions

Integers should be nonnegative. The input is a positive integer and the output is an array separated by new lines.

Solution

So at first, I wanted to cover the first row. It is always going to be an array of [1]. I set the result array to that array. For the case that there are no rows, the output returns an empty array. For two rows, a if loop is used that returns an array pushed in according to line 14. The outer for loop from lines 17–28 is used to loop through all the rows from n=2 to the number of rows given. The use of the last variable is to allow it to output the next row. The next loop is to count from the second index after the initial 1 that appears in every row. It loops till the last index which is last.length-1. Line 23 is a very crucial step. It is going, to sum up two numbers from above to input a number in the temp array. What parseInt allows me to do is to make the string into an integer for the number that occurs at last array index of j and last array index of j+1 and that gets pushed into the temp array. After the numbers are summed up, the last number pushed into the array is a 1. This allows the visual effect to show all ones the side of the pyramid. Returning the result will show every row on a new line.

Conclusion

This solution has a runtime of 44 ms, faster than 97.19% of JavaScript online submissions for Pascal’s Triangle.
Memory Usage: 33.8 MB, less than 100.00% of JavaScript online submissions for Pascal’s Triangle.

This problem is easy to visualize at first but it is kind of hard to keep the summation of numbers going without finding the right number to put for the starting iteration point first. What I learned from this challenge was that creating additional arrays allows me to be more flexible in problem-solving. It becomes easy to retain the information of arrays already created to use for further usage in the problem.

--

--

Kevin W

I like learning about tech, urban design and health/ wellness.