π·οΈ Category: Algorithms / Dynamic Programming | π― Difficulty: Easy | π₯ Frequency: β
β
β
β
β
π Problem Statement
Return the nth Fibonacci Sequence number. The sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21β¦
π₯ Input β n = 6 π€ Output β 8
π₯ Input β n = 10 π€ Output β 55
π₯ Input β n = 0 π€ Output β 0
π§ What the Interviewer is Testing
| Concept | Why It Matters |
|---|---|
| Recursion vs iteration | Trade-off awareness |
| Memoization | Optimization knowledge |
| Time complexity analysis | Understanding exponential growth |
β οΈ Never give just the naive recursive solution. Always show iterative or memoized version.
π‘ Approach
β Naive Recursion β O(2^n) β exponential, very slow
β
Iterative β O(n) β simple and efficient
β
Memoized β O(n) β recursive with caching
β
Matrix / Math β O(logn) β advanced
β Solution 1 β Iterative (Best for interviews)
def fib_iterative(n: int) -> int:
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
# ββ Test Cases βββββββββββββββββββββββββββββββββ
print(fib_iterative(6)) # β
8
print(fib_iterative(10)) # β
55
print(fib_iterative(0)) # β
0
β Solution 2 β Memoized Recursive
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n: int) -> int:
if n <= 1:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(10)) # β
55
β Naive Recursion (for reference β avoid)
# O(2^n) β DO NOT use this in interviews without optimizing
def fib_naive(n: int) -> int:
if n <= 1:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
π Complexity Analysis
ββββββββββββββββββββ¬βββββββββββββ¬βββββββββββββββββββββββββββ
β Approach β Time β Space β
ββββββββββββββββββββΌβββββββββββββΌβββββββββββββββββββββββββββ€
β Naive Recursive β O(2^n) β O(n) call stack β
β Iterative β
β O(n) β O(1) β
β Memoized β
β O(n) β O(n) cache β
ββββββββββββββββββββ΄βββββββββββββ΄βββββββββββββββββββββββββββ
π€ How to Explain in the Interview
βThe naive recursive solution is O(2^n) because it recalculates the same values repeatedly. The iterative approach is O(n) time and O(1) space β just track the previous two values. With lru_cache, we can keep the recursive style while making it O(n) through memoization.β
βThe naive recursive solution is O(2^n) because it recalculates the same values repeatedly. The iterative approach is O(n) time and O(1) space β just track the previous two values. With lru_cache, we can keep the recursive style while making it O(n) through memoization.β
π Common Follow-up Questions
Q1 β Print entire Fibonacci sequence up to n?
def fib_sequence(n: int) -> list:
if n <= 0: return [0]
seq = [0, 1]
while len(seq) <= n:
seq.append(seq[-1] + seq[-2])
return seq[:n+1]
Q2 β Using a generator?
def fib_gen(n: int):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
π Set 1 of 4 β Python Interview Prep Series β devprepguide.com
