Implement Fibonacci with efficiency constraints
Company: Google
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This Coding & Algorithms interview prompt for Data Scientist roles evaluates algorithmic efficiency, dynamic programming principles and numeric-handling considerations by requiring computation of the nth Fibonacci number at very large input sizes; abstraction level: implementation-level algorithmic optimization and complexity analysis.
Constraints
- 0 <= n <= 1,000,000,000
- Use MOD = 1,000,000,007
- Expected time complexity is O(log n)
Examples
Input: (0,)
Expected Output: 0
Explanation: This is the base case: F(0)=0.
Input: (1,)
Expected Output: 1
Explanation: This is the other base case: F(1)=1.
Input: (10,)
Expected Output: 55
Explanation: The 10th Fibonacci number is 55.
Input: (50,)
Expected Output: 586268941
Explanation: F(50)=12586269025, and 12586269025 modulo 1,000,000,007 is 586268941.
Input: (100,)
Expected Output: 687995182
Explanation: F(100)=354224848179261915075, which becomes 687995182 after taking modulo 1,000,000,007.
Input: (1000000,)
Expected Output: 918091266
Explanation: This large input checks that the algorithm is logarithmic rather than linear or exponential.
Hints
- The identities F(2k)=F(k)*(2*F(k+1)-F(k)) and F(2k+1)=F(k)^2+F(k+1)^2 can compute Fibonacci values by repeatedly doubling the index.
- Apply the modulo after additions and multiplications so intermediate values stay small.