Data Structures & AlgorithmsVery hardProduct company OA
Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses.
Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses.
p = 7
fact = [1] * p
for i in range(1, p): fact[i] = fact[i - 1] * i % p
def small(n, r):
if r < 0 or r > n: return 0
return fact[n] * pow(fact[r], p - 2, p) * pow(fact[n - r], p - 2, p) % p
def lucas(n, r):
res = 1
while n or r:
res = res * small(n % p, r % p) % p
n //= p; r //= p
return res
from math import comb
F = [1] * 1001
for i in range(1, 1001): F[i] = F[i - 1] * i % p
naive = F[1000] * pow(F[3] * F[997] % p, p - 2, p) % p
print(lucas(1000, 3), comb(1000, 3) % p, naive)What is printed?- A. 6 6 6
- B. 0 6 0
- C. 6 6 0
- D. 6 0 6
Correct answer: C. 6 6 0
Lucas: write n and r in base p and multiply C(nᵢ, rᵢ) digit by digit. 1000 = (2626)₇ and 3 = (0003)₇ → C(2,0)·C(6,0)·C(2,0)·C(6,3) = 20 ≡ 6 (mod 7), which matches the exact value. The factorial formula breaks because 1000! contains 7 as a factor, so it is 0 mod 7, and 3!·997! is also 0 – its 'Fermat inverse' pow(0, p − 2, p) is 0 – so the naive result is 0. Fermat inverses need values coprime to p; for n ≥ p use Lucas.
More Coding Interview Problems questions
- Problem: Count ways to climb n stairs with steps of 1 or 3, modulo 10⁹ + 7, using a 3 × 3 matrix power so that n up to 10¹⁸ is fine…
- Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and…
- Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a…
- Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median…
- Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest…
- Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current…