Pascal's Triangle II

easy

You're handed a single integer rowIndex. Return exactly that row of Pascal's triangle — using 0-indexed counting, so rowIndex = 0 is the very top [1].

In Pascal's triangle, every number is the sum of the two numbers directly above it. The edges are always 1, and each interior value grows from the pair sitting on its shoulders:

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

Return the row as a flat list of integers, left to right.

Hints

You only need one row — do you actually have to remember every row above it?
Each number equals the sum of the two just above it. If you reuse a single array, which end should you update first so you don't clobber a value before reading it?
Sweep an array of 1s from right to left, doing row[j] += row[j - 1] for each new generation.

Common doubts

0-indexed. rowIndex = 0 returns the single top element [1], and rowIndex = 3 returns [1,3,3,1].
Each slot row[j] needs its left neighbour's OLD value. Going right-to-left means row[j - 1] hasn't been touched yet this pass; going left-to-right would feed it the already-updated value and corrupt the row.
Yes — the k-th entry of row n is the binomial coefficient C(n, k), and you can roll it as row[k] = row[k-1] * (n - k + 1) / k. It's O(rowIndex) time, but watch for overflow and integer-division ordering.

Interview follow-ups

Yes — the optimal solution here uses exactly one array of length rowIndex + 1, which is the answer itself, so no additional row storage is needed.
Use the binomial coefficient C(n, k) directly via the multiplicative formula, giving O(k) time and O(1) space for one entry.

Fun facts

  • Row n of Pascal's triangle is literally the binomial coefficients C(n,0), C(n,1), …, C(n,n) — the coefficients you'd get expanding (a + b)^n.
  • The same right-to-left rolling-array trick powers the space-optimized 0/1 knapsack and coin-change DP solutions.

Asked at

AmazonMicrosoftAdobeGoogle
Frequently Sometimes Occasionally
Example 1
Input: rowIndex = 3
Output: [1,3,3,1]
The 4th row (0-indexed) reads 1, 3, 3, 1 — the middle 3s are 1+2 and 2+1 from row 2.
Example 2
Input: rowIndex = 0
Output: [1]
The very top of the triangle.
Example 3
Input: rowIndex = 1
Output: [1,1]
Two edges, no interior.
Constraints

- 0 <= rowIndex <= 33

Solve this problem →