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?
- A. 120 184756 0
- B. 720 184756 0
- C. 120 184756 1
- 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
- Problem: Find the GCD of all array elements and the LCM of a pair. cpp long long g(long long a, long long b) { return b == 0 ? a : g(b, a…
- Problem: Count trailing zeros of n! (number of factors 5). python def tz(n): c = 0 while n: n //= 5; c += n return c print(tz(25)…
- Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows. python def rev(x): s = -1 if x < 0 else 1 r =…
- Problem: Find the integer x (0 ≤ x < m) such that 3x ≡ 1 (mod 11) using the extended Euclidean algorithm. python def ext(a, b): if b == 0…
- Problem: Return the excel-style column title for a column number (1 → A, 26 → Z, 27 → AA). python def title(n): s = '' while n: n -= 1 s =…
- Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital…