The Pascal Row
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
- Asked in
- Citadel
Problem
An analyst only ever asks for one row of Pascal's triangle at a time: what are the entries of row n (0-indexed), computed directly from the binomial coefficients rather than by building every row above it?
Each number is the sum of two numbers above it.
Example 1
Input:
n = 3
Output:
[1,3,3,1]
Example 2
Input:
n = 0
Output:
[1]
Worked solution and explanation
What this really is
This is a binomial-coefficient recurrence dressed up as a triangle puzzle. Everyone knows the additive build where each entry is the sum of two above it, and that is exactly what the prompt rules out: it materializes every prior row. The skill is carrying C(n, k) forward from C(n, k-1) with one multiply and one divide. The trap is the order of those two operations: divide first and the entries silently truncate to wrong integers.
Walking to the answer
Step 1: Seed the row with C(n, 0)
Every row starts at 1, so row = [1] is both the seed and the full answer for n = 0. No special case needed.
Step 2: Derive each term from the previous one
C(n, k) = C(n, k-1) * (n - k + 1) / k. You already hold C(n, k-1) in row[k - 1], so each new entry costs constant work and no factorials.
Step 3: Multiply first, then floor-divide
The product row[k - 1] * (n - k + 1) is always divisible by k, but row[k - 1] alone usually is not. For n = 5, k = 2: 5 // 2 * 4 gives 8, while 5 * 4 // 2 gives the correct 10.
The solution
def pascal_row(n):
row = [1]
for k in range(1, n + 1):
val = row[k - 1] * (n - k + 1) // k
row.append(val)
return rowCommon follow-up questions
- How would you exploit the row's symmetry to halve the work? (Tests noticing `C(n, k) = C(n, n - k)`.)
- What if you needed the entire triangle up to row `n`? (Tests switching back to the additive build when it is actually the right tool.)
- What changes in a language with fixed-width integers and `n` in the thousands? (Tests awareness of overflow in the intermediate product.)