15. Pascal's Triangle
easyAsked at TripAdvisorGenerate the first numRows of Pascal's triangle.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
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.
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. Closed-form binomial
Compute row i with nCk via factorial.
- Time
- O(n^2)
- Space
- O(n^2)
// computing factorials each time wastes work
// and accumulates rounding error for larger nTradeoff:
2. Build row from previous
Row[i] = sum of adjacent entries in row[i-1]. Edges always 1.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const rows = [];
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
row[j] = rows[i-1][j-1] + rows[i-1][j];
}
rows.push(row);
}
return rows;
}Tradeoff:
TripAdvisor-specific tips
TripAdvisor uses combinatorial table problems to gauge if you precompute aggregates instead of recomputing per request.
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 TripAdvisor interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →