Skip to main content

15. Pascal's Triangle

easyAsked at Unity

Generate the first numRows of Pascal's triangle. Unity uses this to test row-allocation discipline in batched mesh buffers.

By Alex Chen, 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=5
Output
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2

Input
numRows=1
Output
[[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.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Pascal's Triangle and other Unity interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →