Fibonacci Number
LeetCode 509 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
F(i) only depends on F(i-1) and F(i-2), so two rolling variables are enough.
நான் Fibonacci Number (LeetCode 509) ஐ இப்படித் தீர்த்தேன் — 1D / Fibonacci பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Each Fibonacci number is the sum of the two before it. A direct recursive definition works but recomputes the same values over and over; storing them turns an exponential call tree into a straight line.
Approach
- 1
Handle the two seeds: F(0) = 0 and F(1) = 1.
- 2
Recursive version: return fib(n-1) + fib(n-2) — correct but repeats work.
- 3
Tabulation: fill dp[i] = dp[i-1] + dp[i-2] for i from 2 to n.
- 4
Space-optimise: keep prev2 and prev, compute cur, then shift both forward.
நான் எப்படித் தீர்த்தேன் · முதல் யோசனையிலிருந்து இறுதித் தீர்வு வரை
Straight from the definition — watch how often the same calls repeat.
Build the sequence in an array.
Roll prev2 → prev → cur forward.
Plain recursionPythonO(2ⁿ) time · O(n) stack
class Solution:
def fib(self, n: int) -> int:
if n==0:
return 0
if n==1:
return 1
return self.fib(n-1)+self.fib(n-2)TabulationPythonO(n) time · O(n) space
class Solution:
def fib(self, n: int) -> int:
if n==0:
return 0
if n==1:
return 1
dp=[0]*(n+1)
dp[0]=0
dp[1]=1
for i in range(2,n+1):
dp[i]=dp[i-1]+dp[i-2]
return dp[n]Two variablesPythonO(n) time · O(1) space
class Solution:
def fib(self, n: int) -> int:
if n==0:
return 0
if n==1:
return 1
dp=[0]*(n+1)
prev2=0
prev=1
for i in range(2,n+1):
cur = prev+prev2
#prev2 prev cur
# prev2 prev
prev2=prev
prev=cur
return prevFibonacci Number — அடிக்கடி கேட்கப்படும் கேள்விகள்
Fibonacci Number பின்னாலுள்ள intuition என்ன?
Each Fibonacci number is the sum of the two before it. A direct recursive definition works but recomputes the same values over and over; storing them turns an exponential call tree into a straight line.
Fibonacci Number (LeetCode 509) ஐ எப்படித் தீர்ப்பது?
1. Handle the two seeds: F(0) = 0 and F(1) = 1. 2. Recursive version: return fib(n-1) + fib(n-2) — correct but repeats work. 3. Tabulation: fill dp[i] = dp[i-1] + dp[i-2] for i from 2 to n. 4. Space-optimise: keep prev2 and prev, compute cur, then shift both forward.
Fibonacci Number இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(1). (Accepted approach: Two variables.)
Fibonacci Number இல் பொதுவான தவறுகள் என்ன?
The naive recursion is O(2^n) — fine for n ≤ 30 here, but it is the classic reason to memoise. Return early for n = 0 and n = 1 before indexing dp[1].
Fibonacci Number ஐத் தீர்க்க ஒன்றுக்கு மேற்பட்ட வழிகள் உள்ளனவா?
Plain recursion (O(2ⁿ) time · O(n) stack): Straight from the definition — watch how often the same calls repeat. Tabulation (O(n) time · O(n) space): Build the sequence in an array. Two variables (O(n) time · O(1) space): Roll prev2 → prev → cur forward.