Code Room
CodingHardcod-g834
Subject Combinatorial countingLevel Senior–Staff~35 minCommon in Algorithms & data structures interviewsIndustries Software development

Question

Compute C(n, r) (n choose r) modulo a prime p, where n and r can be large (up to 10^9) while p is a small prime (e.g. up to 10^4). Direct factorials overflow the modulus structure when n >= p, so apply Lucas' theorem: express n and r in base p, multiply the per-digit small binomials C(n_i, r_i) mod p (each computed with Fermat-inverse denominators), and return 0 if any digit r_i exceeds n_i. Return 0 when r < 0 or r > n.

Implement
binomial_mod_p(n: int, r: int, p: int) → int
Examples
in[10,3,13]out3
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.