Skip to main content

15. Pascal's Triangle

easyAsked at Zoom

Generate the first numRows of Pascal's triangle.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer numRows, return the first numRows of Pascal's triangle. Each number is the sum of the two directly above it.

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. Combinatorial

Use C(n,k) formula for each cell.

Time
O(n^2)
Space
O(n^2)
function C(n,k){let r=1n; for(let i=0;i<k;i++) r=r*BigInt(n-i)/BigInt(i+1); return Number(r);}

Tradeoff:

2. Row-by-row build

Each row is built from the previous; sum adjacent pairs.

Time
O(n^2)
Space
O(n^2)
function generate(numRows) {
  const tri = [];
  for (let i = 0; i < numRows; i++) {
    const row = new Array(i + 1).fill(1);
    for (let j = 1; j < i; j++) {
      row[j] = tri[i - 1][j - 1] + tri[i - 1][j];
    }
    tri.push(row);
  }
  return tri;
}

Tradeoff:

Zoom-specific tips

Zoom tests this as a warmup for additive aggregate problems found in audio-meter rolling-window math; demonstrate clean 2D array construction.

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 Zoom interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →