14. Pascal's Triangle
easyAsked at Electronic ArtsGenerate the first numRows rows of Pascal's triangle, testing 2D array construction skills valued in EA's simulation and math-heavy game code.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows rows 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
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 nested loops
Build each row by iterating through previous row and summing adjacent pairs.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const res = [[1]];
for (let i = 1; i < numRows; i++) {
const prev = res[i - 1];
const row = [1];
for (let j = 1; j < i; j++) row.push(prev[j-1] + prev[j]);
row.push(1);
res.push(row);
}
return res;
}Tradeoff:
2. Optimal iterative build
Same O(n²) but clean with spread: each row is derived in one pass from the previous, which is also the optimal approach since output itself is O(n²).
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
return Array.from({ length: numRows }, (_, i) => {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) {
row[j] = prev[j-1] + prev[j]; // use triangle[i-1]
}
return row;
}).reduce((acc, _, i, src) => {
const row = new Array(i + 1).fill(1);
for (let j = 1; j < i; j++) row[j] = acc[i-1][j-1] + acc[i-1][j];
acc.push(row);
return acc;
}, [[1]]).slice(0, numRows);
}Tradeoff:
Electronic Arts-specific tips
EA interviews cover game development data structures, pathfinding (A*, BFS on grids), spatial algorithms, and simulation problems. Grid/matrix manipulation and BFS on 2D arrays are very common.
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 Electronic Arts interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →