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?- A. [1, 1, 2, 3, 4, 6, 9] False 122106097
- B. [1, 2, 3, 4, 6, 9, 13] True 122106097
- C. [1, 1, 2, 3, 4, 6, 9] True 83316385
- 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
- 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…
- Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo…