Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime).

Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime).
M = 10**9 + 7
N = 20
fact = [1] * (N + 1)
for i in range(1, N + 1): fact[i] = fact[i - 1] * i % M
inv = [1] * (N + 1)
inv[N] = pow(fact[N], M - 2, M)
for i in range(N, 0, -1): inv[i - 1] = inv[i] * i % M
C = lambda n, r: 0 if r < 0 or r > n else fact[n] * inv[r] % M * inv[n - r] % M
print(C(10, 3), C(20, 10), C(5, 7))
What is printed?
  1. A. 120 184756 0
  2. B. 720 184756 0
  3. C. 120 184756 1
  4. D. 120 92378 0

Correct answer: A. 120 184756 0

C(10,3) = 120 and C(20,10) = 184756. Inverse factorials come from one Fermat inverse a^(p−2) and the recurrence inv[i−1] = inv[i]·i. r > n has no ways → 0. Precomputation O(N + log M), each query O(1). Dividing factorials with / under a modulus is the classic error.

More Coding Interview Problems questions

Exams that ask this topic