Data Structures & AlgorithmsVery hardProduct company OA

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: 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.
MOD = 10**9 + 7
def mat_mul(A, B):
    return [[sum(A[i][k] * B[k][j] for k in range(len(B))) % MOD for j in range(len(B[0]))] for i in range(len(A))]
def ways(n):
    M = [[1, 0, 1], [1, 0, 0], [0, 1, 0]]
    R = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    while n:
        if n & 1: R = mat_mul(R, M)
        M = mat_mul(M, M); n >>= 1
    return R[0][0]
f = [1, 1, 1]
for i in range(3, 51): f.append(f[-1] + f[-3])
print([ways(n) for n in range(1, 8)], ways(50) == f[50] % MOD, f[50] % MOD)
What is printed?
  1. A. [1, 1, 2, 3, 4, 6, 9] False 122106097
  2. B. [1, 2, 3, 4, 6, 9, 13] True 122106097
  3. C. [1, 1, 2, 3, 4, 6, 9] True 83316385
  4. D. [1, 1, 2, 3, 4, 6, 9] True 122106097

Correct answer: D. [1, 1, 2, 3, 4, 6, 9] True 122106097

f(n) = f(n − 1) + f(n − 3) with f(0) = f(1) = f(2) = 1. The state vector (f(n), f(n − 1), f(n − 2)) is multiplied by [[1, 0, 1], [1, 0, 0], [0, 1, 0]], so f(n) is the top-left entry of Mⁿ: 1, 1, 2, 3, 4, 6, 9 for n = 1..7. The fast power uses O(log n) 3 × 3 multiplications, and f(50) agrees with the plain DP (122106097 mod 10⁹ + 7). Off-by-one in the base vector shifts the sequence by one.

More Coding Interview Problems questions

Exams that ask this topic