Single Row of the Binomial Triangle in Linear Space
Math & Bit ManipulationAuto-graded · 19 test casesLast updated
Compute one row of Pascal's triangle by index, using only space proportional to the row, via an in-place update or the multiplicative binomial recurrence.
Binomial Triangle Row
Consider the triangle in which the top row contains a single 1, and every other row starts and ends with 1, while each inner value equals the sum of the two values directly above it (the one up-left and the one up-right).
Rows are numbered from 0:
- row
0is[1] - row
1is[1, 1] - row
2is[1, 2, 1] - row
3is[1, 3, 3, 1]
Given a non-negative integer n, return row number n as a list of integers. Row n contains exactly n + 1 values.
Aim to do this without storing the whole triangle; memory proportional to the size of the output row is enough.
Input
n: an integer, the 0-based index of the requested row.
Output
- A list of
n + 1integers: the entries of rown, from left to right.
Constraints
0 <= n <= 33- Rows are 0-indexed.
- The returned values are exact integers (no floating-point results).
Examples
Example 1
Input: pascal_row(0)
Output: [1]
Example 2
Input: pascal_row(3)
Output: [1, 3, 3, 1]
Example 3
Input: pascal_row(5)
Output: [1, 5, 10, 10, 5, 1]
Hints
Hint 1
Row n holds the binomial coefficients C(n, 0), C(n, 1), ..., C(n, n).
Hint 2
Each coefficient can be derived from the one before it: C(n, j) = C(n, j-1) * (n - j + 1) / j.
Hint 3
Multiply first and then use integer division; the result is always exact, so there is no need for floats or factorials.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Row n of the triangle consists of the binomial coefficients C(n, 0), C(n, 1), ..., C(n, n). Consecutive coefficients are related by
C(n, j) = C(n, j-1) * (n - j + 1) / j
So we start with 1 (which is C(n, 0)) and repeatedly compute the next entry from the previous one. We multiply before dividing, so the division by j is always exact.
Why it is correct
From C(n, j) = n! / (j! (n-j)!), the ratio C(n, j) / C(n, j-1) simplifies to (n - j + 1) / j. The product C(n, j-1) * (n - j + 1) equals j * C(n, j), which is divisible by j, so integer division gives the exact value. By induction on j, every entry is correct. For n = 0 the loop does not run and the result is [1].
An alternative is an in-place update: append a 1 for each new row and then update inner entries from right to left with row[j] += row[j-1]. That takes O(n²) time, whereas the formula needs only O(n).
Complexity
- Time: O(n) arithmetic operations.
- Space: O(n) for the output row, which is optimal.
Reference solution
from typing import List
def pascal_row(n: int) -> List[int]:
row = [1]
for j in range(1, n + 1):
row.append(row[-1] * (n - j + 1) // j)
return row