Skip to main content

15. Pascal's Triangle

easyAsked at Coursera

Generate the first numRows of Pascal's triangle, an iterative DP warm-up Coursera uses to test basic 2-D array construction.

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

Problem

Given an integer numRows, return the first numRows 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

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. Brute force (recompute each row from scratch)

For each position sum the two values in the previous row without storing the triangle incrementally.

Time
O(n^2)
Space
O(n^2)
// Readable but no different in complexity
function generate(numRows) {
  const res = [];
  for (let i = 0; i < numRows; i++) {
    const row = Array(i + 1).fill(1);
    for (let j = 1; j < i; j++) row[j] = res[i-1][j-1] + res[i-1][j];
    res.push(row);
  }
  return res;
}

Tradeoff:

2. Incremental row build

Build each new row directly from the last stored row, filling edges with 1s and interior cells as prev[j-1]+prev[j]. Clean O(n^2) time and space, optimal for this problem.

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

Tradeoff:

Coursera-specific tips

Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.

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

Practice these live with InterviewChamp.AI →