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.