Skip to main content

9. Pascal's Triangle

easyAsked at LINE

Generate the first n rows of Pascal's triangle — LINE uses this to check that you can build up tabular data without off-by-one errors before moving into sticker-pack pagination.

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 formula

Compute C(n,k) for every cell using factorials.

Time
O(n^2)
Space
O(n^2)
const fact=n=>{let r=1n;for(let i=2n;i<=BigInt(n);i++)r*=i;return r;};
// res[i][k] = fact(i)/(fact(k)*fact(i-k))
// O(n) per cell from naive factorials.

Tradeoff:

2. Row-by-row DP

Build each row from the previous: row[k] = prev[k-1] + prev[k]. Edges are always 1. Reuses prior work in O(n^2).

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

Tradeoff:

LINE-specific tips

At LINE, mention that the same row-from-previous-row trick keeps sticker grid pagination O(1) extra memory per page — concrete delivery-pipeline framing wins.

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

Practice these live with InterviewChamp.AI →