Magicsheet logo

Pascal's Triangle

Easy
55.3%
Updated 6/1/2025

Pascal's Triangle

What is this problem about?

Pascal's Triangle is one of the most fundamental problems in combinatorics and dynamic programming. Given numRows, generate the first numRows rows of Pascal's triangle, where each element is the sum of the two elements directly above it. This easy coding problem tests 2D array construction with the recurrence relation. The array and dynamic programming interview pattern is demonstrated.

Why is this asked in interviews?

J.P. Morgan, Cisco, Uber, Goldman Sachs, Oracle, Google, and many others ask this as a warm-up problem. It tests basic 2D array construction, recurrence relations, and base case handling. It's also a gateway to combinatorial math (binomial coefficients).

Algorithmic pattern used

Row-by-row DP construction. Each row starts and ends with 1. For row i and position j (1 ≤ j ≤ i-1): triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]. Build row by row.

Example explanation

numRows=5. Build rows:

  • Row 0: [1]
  • Row 1: [1,1]
  • Row 2: [1,2,1]
  • Row 3: [1,3,3,1]
  • Row 4: [1,4,6,4,1] Result: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].

Common mistakes candidates make

  • Off-by-one in inner loop (must fill positions 1..row-1, not 0..row).
  • Not initializing first and last elements of each row to 1.
  • Modifying the previous row in-place (must use new row array).
  • Not handling numRows=0 or numRows=1 edge cases.

Interview preparation tip

Pascal's Triangle builds the foundation for understanding binomial coefficients: C(n,k) = triangle[n][k]. Practice generating it iteratively (build row by row) and recognize its applications: combinatorics, probability, and polynomial expansion. After this, solve Pascal's Triangle II (kth row only with O(k) space) to reinforce space optimization skills.

Similar Questions