15. Pascal's Triangle
easyAsked at UnityGenerate the first numRows of Pascal's triangle. Unity uses this to test row-allocation discipline in batched mesh buffers.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an integer numRows, return the first numRows of Pascal's triangle as a list of lists.
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. Factorial formula
Compute each C(n,k) via factorials.
- Time
- O(n^2)
- Space
- O(n^2)
const fact = n => n<=1?1:n*fact(n-1);
// row r col c = fact(r)/(fact(c)*fact(r-c))Tradeoff:
2. Iterative previous row sum
Each new row's interior is the pairwise sum of the previous row.
- Time
- O(n^2)
- Space
- O(n^2)
function generate(n) {
const rows = [];
for (let i=0;i<n;i++) {
const row = new Array(i + 1).fill(1);
for (let j=1;j<i;j++) row[j] = rows[i-1][j-1] + rows[i-1][j];
rows.push(row);
}
return rows;
}Tradeoff:
Unity-specific tips
Unity grades for preallocated rows (`new Array(i+1)`) since batched mesh buffers must avoid resizing inside the per-frame budget.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Unity 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. Plus One
- 8. Merge Sorted Array