KatInterview

Single Row of the Binomial Triangle in Linear Space

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationpascal-trianglecombinatoricsdynamic-programming

Last 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 0 is [1]
  • row 1 is [1, 1]
  • row 2 is [1, 2, 1]
  • row 3 is [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 + 1 integers: the entries of row n, 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.