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.