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?
  1. A. 55 12586269025
  2. B. 89 586268941
  3. C. 55 586268941
  4. 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

Exams that ask this topic