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

Pascal's Triangle II

EasyArrays

Pascal's triangle starts with a single 1 at the top. Each row below it begins and ends with 1, and every entry between the ends equals the two entries diagonally above it added together.

Given rowIndex, return that row of the triangle, counting the top row as row 0.

Example 1

Input:  rowIndex = 4
Output: [1, 4, 6, 4, 1]
Why:    row 3 is 1 3 3 1, and 1+3, 3+3, 3+1 fill the middle
2 more examples and the constraints

Example 2

Input:  rowIndex = 0
Output: [1]
Why:    the top of the triangle is a single 1

Example 3

Input:  rowIndex = 5
Output: [1, 5, 10, 10, 5, 1]
Why:    the sums of neighbours in row 4

Constraints

  • 0 ≤ rowIndex ≤ 33
  • Try to use only O(rowIndex) extra space

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. Build every rowO(k²)
  2. One row, updated in placeO(k²)
  3. Binomial formulaO(k)

The idea in one sentence

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

Side by side

ApproachTimeSteps for rowIndex = 33Verdict
Build every rowO(k²)
Correct; keeps the whole triangle
One row in placeO(k²)
Meets the O(k) space goal
Binomial formulaO(k)
Best; one pass

k = rowIndex.

Edge cases to test

  • Row 0. Returns [1]; both loops run zero times.
  • Row 1. Returns [1, 1]; there is no middle entry.
  • Row 33. The middle values reach 1,166,803,110, which fits in a 32-bit int, but the product inside the formula does not.

Common mistakes

  • Updating the single row from left to right, so each cell adds an already-updated neighbour.
  • Dividing before multiplying in the formula, which loses the remainder and gives wrong values.
  • Using a 32-bit int for row[j − 1] × (k − j + 1) near row 33.

How to talk through it

  1. 1Clarify. Is the top row number 0? Only one row is returned, not the whole triangle?
  2. 2State the rule. Ends are 1; each middle entry adds the two above it.
  3. 3Save space. One array is enough if you update it from right to left, so the old values are still there when you read them.
  4. 4Use the formula. Entry j is C(k, j); each one is the previous times (k − j + 1) / j, so the row takes O(k).
  5. 5Test out loud. Run row 0, row 1 and row 4, and mention the overflow at row 33.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?