🚀Day 13/180 509. Fibonacci Number (Leetcode)
#180DaysOfDSA#DailyCodingChallenge #LeetCodeJourney #GeeksforGeeks #CodingNinjas #Codechef #CodeForces #ContinuousLearning #TechCommunity

Sure, let's do a dry run of the provided recursive function for n = 4.
Here is the code again for reference:
class Solution {
public int fib(int n) {
if (n == 1 || n == 0) {
return n;
}
int first = fib(n - 1);
int second = fib(n - 2);
return first + second;
}
}
Dry Run for n = 4:
Call
fib(4)nis neither 0 nor 1, so we proceed to calculatefib(3)andfib(2).
Call
fib(3)nis neither 0 nor 1, so we proceed to calculatefib(2)andfib(1).
Call
fib(2)nis neither 0 nor 1, so we proceed to calculatefib(1)andfib(0).
Call
fib(1)nis 1, so we return 1.
Call
fib(0)nis 0, so we return 0.
Return to
fib(2)We have
fib(1) = 1andfib(0) = 0.fib(2)returns1 + 0 = 1.
Return to
fib(3)- We have
fib(2) = 1(from step 6) and need to calculatefib(1)again.
- We have
Call
fib(1)nis 1, so we return 1.
Return to
fib(3)We have
fib(2) = 1andfib(1) = 1.fib(3)returns1 + 1 = 2.
Return to
fib(4)- We have
fib(3) = 2(from step 9) and need to calculatefib(2)again.
- We have
Call
fib(2)nis neither 0 nor 1, so we proceed to calculatefib(1)andfib(0).
Call
fib(1)nis 1, so we return 1.
Call
fib(0)nis 0, so we return 0.
Return to
fib(2)We have
fib(1) = 1andfib(0) = 0.fib(2)returns1 + 0 = 1.
Return to
fib(4)We have
fib(3) = 2andfib(2) = 1.fib(4)returns2 + 1 = 3.
Final Result:
The call fib(4) returns 3, which is the 4th Fibonacci number.
The recursive calls create a tree-like structure where many subproblems are solved multiple times, indicating the inefficiency of this approach.