15. Pascal's Triangle
easyAsked at BoxGenerate the first numRows of Pascal's triangle — Box uses this row-building pattern as a warm-up for index-array manipulation in metadata layouts.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows of Pascal's triangle.
Constraints
1 <= numRows <= 30
Examples
Example 1
Input
numRows = 5Output
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Example 2
Input
numRows = 1Output
[[1]]Approaches
1. Combinatorial
Compute each cell with C(n,k) factorial formula.
- Time
- O(n^2)
- Space
- O(n^2)
function C(n,k){ let r=1; for(let i=0;i<k;i++) r = r*(n-i)/(i+1); return Math.round(r); }
// fill triangle via CTradeoff:
2. Row-by-row sum
Each row built from the prior by adding adjacent values, with 1s at the ends.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(n) {
const t = [];
for (let i = 0; i < n; i++) {
const row = new Array(i+1).fill(1);
for (let j = 1; j < i; j++) row[j] = t[i-1][j-1] + t[i-1][j];
t.push(row);
}
return t;
}Tradeoff:
Box-specific tips
Box wants the row-by-row construction with bounded allocations — they map it to building per-folder index-row tables for the file-listing API.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Box coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Plus One
- 8. Merge Sorted Array