progress

~/problems / Counting / Combinatorics / inclusion-exclusion

Binomial coefficients with Pascal's triangle

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

C(n, k), "n choose k", counts the ways to pick k of n distinct items: the building block of most counting formulas.

Write pascal(n: int) -> list[list[int]] returning rows 0..n of Pascal's triangle, so pascal(n)[i][k] == C(i, k). Use the recurrence, not math.comb or factorials:

  • C(i, 0) = C(i, i) = 1
  • C(i, k) = C(i-1, k-1) + C(i-1, k): item i is either picked or not.
pascal(0)   # [[1]]
pascal(4)   # [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
pascal(6)[6][2]   # 15: choose 2 of 6

0 <= n <= 500. The numbers get huge; Python ints cope, so no modulus.

⭐ Bonus: a speed test with all 500 rows earns a star if each row comes from the previous one in O(i).

Show hint

each row comes from the previous: [1] + [prev[k-1] + prev[k] for k in range(1, i)] + [1].

Topic: Combinatorics / inclusion-exclusion. Stars and bars, nCr identities, |A u B| = |A| + |B| - |A n B|.

0:00
Ctrl ' run · Ctrl ↵ submit
esc