15. Pascal's Triangle
easyAsked at CircleCIGenerate Pascal's triangle up to numRows, testing your ability to build iterative tabular structures common in test-result matrix generation at CircleCI.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows of Pascal's triangle, where 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 by summing adjacent elements from the previous row.
- 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 < prev.length; j++) row.push(prev[j-1] + prev[j]);
row.push(1);
res.push(row);
}
return res;
}Tradeoff:
2. In-place row construction
Same iterative approach but emphasizes clarity of boundary conditions, demonstrating clean code under interview pressure.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(numRows) {
const triangle = [];
for (let i = 0; i < numRows; i++) {
const row = new Array(i + 2).fill(1);
for (let j = 1; j < i; j++) {
row[j] = triangle[i-1][j-1] + triangle[i-1][j];
}
row.pop();
triangle.push(row.slice(0, i + 1));
}
return triangle;
}Tradeoff:
CircleCI-specific tips
CircleCI may ask this as a warmup before pivoting to 2D DP — be prepared to extend to Pascal's triangle row access in O(k) space.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More CircleCI coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Maximum Subarray
- 8. Plus One