15. Pascal's Triangle
easyAsked at IndeedGenerate the first numRows rows of Pascal's triangle — tests iterative 2D array construction that mirrors Indeed's incremental ranking coefficient tables.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows of Pascal's triangle. Each row is built so that 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. Brute force
Build each row from scratch using binomial coefficients.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const res = [];
for (let i = 0; i < numRows; i++) {
const row = [1];
for (let j = 1; j < i; j++) row.push(res[i-1][j-1] + res[i-1][j]);
if (i > 0) row.push(1);
res.push(row);
}
return res;
}Tradeoff:
2. Previous-row reference
Each row starts and ends with 1; interior values derive from the previous row, giving clean O(n^2) time with no unnecessary recomputation.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const triangle = [[1]];
for (let i = 1; i < numRows; i++) {
const prev = triangle[i - 1];
const row = [1];
for (let j = 1; j < i; j++) row.push(prev[j - 1] + prev[j]);
row.push(1);
triangle.push(row);
}
return triangle;
}Tradeoff:
Indeed-specific tips
Indeed appreciates clean off-by-one handling on the first and last element of each row — state the boundary invariant aloud before coding.
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 Indeed interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →