Pascal's Triangle
Given an integer numRows, return the first numRows of Pascal's triangle . In Pascal's triangle, each row starts and ends with 1, and every other number is the sum of the two numbers above it in the previous row. Build each row from the previous row instead of recomputing sums from scratch.
Constraints
- 1 ≤ numRows ≤ 30
Example
numRows = 5[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]Explanation Each inner value is the sum of the two values above it in the previous row, for example 1+2=3, 2+1=3, and so on.
In plain terms
- Pascal's triangle
- A triangular arrangement of numbers where each row is built from the row above it, commonly used to show combinations and binomial coefficients.
The row is the newest triangle row, kept at its widest size with blanks
Row 0 is always [1]. Only the first slot is in use, so the other three stay blank.
What happens in this step
row 0 = [1] result = [[1]]
Steps to visualize
- The row below always has four slots, because the last row we build is four numbers wide.
- A slot showing — is not part of the triangle row yet.
- Start with the first row, which is just [1].
- For each new row, start and end it with 1, and fill every middle slot with the sum of the two values above it.
- The highlight box covers the slots the current row is using.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Row 0 is always [1]. Only the first slot is in use, so the other three stay blank.
What happens in this step
row 0 = [1] result = [[1]]
Solution
function generate(numRows) {
const result = [[1]];
for (let r = 1; r < numRows; r++) {
const previous = result[r - 1];
const row = [1];
for (let i = 1; i < r; i++) {
row.push(previous[i - 1] + previous[i]);
}
row.push(1);
result.push(row);
}
return result;
}- Time
- O(numRows^2)
- Space
- O(numRows^2)
Test cases
| Input | Expected | Covers |
|---|---|---|
numRows = 5 | [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] | example from the docstring |
numRows = 1 | [[1]] | smallest valid input, a single row |
numRows = 2 | [[1], [1, 1]] | boundary case, exactly two rows |
numRows = 3 | [[1], [1, 1], [1, 2, 1]] | smallest case with a computed middle value |
numRows = 6 | [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]] | larger triangle with multiple computed middle values |