15. Pascal's Triangle
easyAsked at EtsyGenerate the first numRows of Pascal's Triangle — Etsy uses it as a clean iteration warmup.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows of Pascal's triangle. Each row builds from the row above by summing adjacent entries.
Constraints
1 <= numRows <= 30
Examples
Example 1
numRows = 5[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]Example 2
numRows = 1[[1]]Approaches
1. Binomial formula
Compute C(n, k) for each cell using factorials.
- Time
- O(n^2)
- Space
- O(n^2)
function fact(x){ let r = 1n; for (let i=2n;i<=BigInt(x);i++) r*=i; return r; }
function C(n,k){ return Number(fact(n)/(fact(k)*fact(n-k))); }
return Array.from({length:numRows},(_,r)=>Array.from({length:r+1},(_,c)=>C(r,c)));Tradeoff:
2. Roll forward
Each row = prev row with adjacent sums, padded by 1s on each end.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const rows = [];
for (let r = 0; r < numRows; r++) {
const row = new Array(r+1).fill(1);
for (let c = 1; c < r; c++) row[c] = rows[r-1][c-1] + rows[r-1][c];
rows.push(row);
}
return rows;
}Tradeoff:
Etsy-specific tips
Etsy interviewers care about clean indexing and clear loops — they're alert to off-by-one mistakes more than fancy formulas.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Pascal's Triangle and other Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →