16. Pascal's Triangle
easyAsked at ExpediaGenerate 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. Each number is the sum of the two numbers directly above it.
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. Combinatoric formula
Compute each entry as C(n,k).
- 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 r;}Tradeoff:
2. Build row from previous
Each row[i] = prev[i-1] + prev[i]. Expedia uses similar row-by-row buildups for cumulative price tables.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const tri = [];
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
row[j] = tri[i - 1][j - 1] + tri[i - 1][j];
}
tri.push(row);
}
return tri;
}Tradeoff:
Expedia-specific tips
Expedia values the build-from-previous-row approach; mention it's the same pattern as building cumulative night-by-night price tables for stays.
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 Expedia interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →