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.