15. Pascal's Triangle
easyAsked at SlackReturn 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 entry 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. Combinatorics formula
Compute each cell via nCr.
- Time
- O(n^2)
- Space
- O(n^2)
function comb(n,k){ let r=1; for(let i=0;i<k;i++) r=r*(n-i)/(i+1); return r; }
return Array.from({length:numRows},(_,i)=>Array.from({length:i+1},(_,j)=>comb(i,j)));Tradeoff:
2. Iterative row-from-prev
Build each row by summing adjacent entries of the previous row. Both ends are 1.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const out = [];
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
row[j] = out[i - 1][j - 1] + out[i - 1][j];
}
out.push(row);
}
return out;
}Tradeoff:
Slack-specific tips
Slack engineers like the iterative approach because it mirrors how they pre-compute UI-grid layouts row-by-row.
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 Slack interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →