Skip to content
Problem 118 · LeetCode 118(opens in a new tab)

Pascal's Triangle

EasyArrays

Pascal's triangle is a stack of rows of numbers. The top row is just 1. Each row below is one longer: it begins and ends with 1, and each entry in between equals the two entries diagonally above it added together.

Given numRows, return the first numRows rows of the triangle, top row first, each as a list.

Example 1

Input:  numRows = 3
Output: [[1], [1, 1], [1, 2, 1]]
Why:    the 2 is 1 + 1 from the row above
1 more example and the constraints

Example 2

Input:  numRows = 2
Output: [[1], [1, 1]]
Why:    the second row is only its two ends

Constraints

  • 1 ≤ numRows ≤ 30

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Each entry from its formulaO(n³)
  2. Build each row from the one aboveO(n²)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30 rowsVerdict
Each entry from its formulaO(n³)
Passes; repeats work
Build each row from the one aboveO(n²)
Best; one addition per entry

n = numRows.

Edge cases to test

  • One row. numRows = 1 gives [[1]]; the inner loop never runs.
  • Two rows. Row 1 is [1, 1] with no middle; do not read a row −1.
  • Thirty rows. The largest entry, C(29, 14) = 77,558,760, fits in 32 bits.

Common mistakes

  • Off-by-one rows: returning numRows + 1 rows, or numRows − 1.
  • Appending the same list object every time in Python or Java, so all rows change together.
  • Starting the inner loop at k = 0, which reads prev[−1].

How to talk through it

  1. 1Clarify. Is the first row [1]? Should I return numRows rows, top first?
  2. 2State the rule. Ends are 1; inside, each entry is the sum of the two above it.
  3. 3Mention the formula. Entries are C(r, k), but computing each alone repeats work and risks overflow.
  4. 4Code it row by row. Make r + 1 ones, fill k from 1 to r − 1 from the previous row, append.
  5. 5Test out loud. Run numRows = 1, 2 and 3.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?