Pascal's Triangle Using Nested Loops

Hard ⏱ 18 min 32% acceptance ★★★★☆ 4.2
Write a function pascals_triangle(n) that returns the first n rows of Pascal's Triangle as a list of lists, where each row is computed iteratively from the previous row (do not use math.comb).

Examples

Example 1
Input
pascals_triangle(4)
Output
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]]
Explanation

Each interior value is the sum of the two values above it in the previous row.

Constraints

  • n is a positive integer.
  • Must not use math.comb or a direct binomial coefficient formula.

Topics

Loopsnested loopsaccumulator

Companies

GoogleMetaMicrosoft

Hints

Hint 1

Start with row [1], then for each new row, build it from the previous row: edges are always 1, interior values sum adjacent pairs from the previous row.

Hint 2

A nested loop over row index and column index works well.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.