Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n).
Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n).
MOD = 10**9 + 7
def mul(A, B):
return [[(A[0][0]*B[0][0] + A[0][1]*B[1][0]) % MOD, (A[0][0]*B[0][1] + A[0][1]*B[1][1]) % MOD],
[(A[1][0]*B[0][0] + A[1][1]*B[1][0]) % MOD, (A[1][0]*B[0][1] + A[1][1]*B[1][1]) % MOD]]
def fib(n):
R, M = [[1, 0], [0, 1]], [[1, 1], [1, 0]]
while n:
if n & 1: R = mul(R, M)
M = mul(M, M); n >>= 1
return R[0][1]
print(fib(10), fib(50))What is printed?- A. 55 12586269025
- B. 89 586268941
- C. 55 586268941
- D. 55 586268942
Correct answer: C. 55 586268941
[[1,1],[1,0]]ⁿ = [[F(n+1), F(n)], [F(n), F(n−1)]], so R[0][1] = F(n). F(10) = 55 and F(50) = 12,586,269,025 ≡ 12,586,269,025 − 12 × (10⁹ + 7) = 55 586268941 after reduction. Forgetting the modulus gives the raw value.
More Coding Interview Problems questions
- Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth). python…
- Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight). python from functools import…
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…