Fibonacci Using DP in DSA C - Time & Space Complexity
We want to understand how fast the Fibonacci sequence calculation runs when using dynamic programming.
Specifically, how the number of steps grows as the input number increases.
Analyze the time complexity of the following code snippet.
int fibonacci(int n) {
int dp[n+1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
This code calculates the nth Fibonacci number by storing previous results to avoid repeated work.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 2 to n, calculating each Fibonacci number once.
- How many times: Exactly n-1 times, once for each number from 2 up to n.
Each new Fibonacci number is calculated once using two previous results, so work grows steadily with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 8 additions |
| 100 | About 98 additions |
| 1000 | About 998 additions |
Pattern observation: The number of operations grows roughly in a straight line as n increases.
Time Complexity: O(n)
This means the time to compute the Fibonacci number grows directly in proportion to the input size.
[X] Wrong: "Calculating Fibonacci with recursion is always fast because it just calls itself."
[OK] Correct: Simple recursion repeats many calculations, making it much slower than this dynamic programming approach.
Understanding how dynamic programming improves speed by saving past results is a key skill that shows you can optimize solutions thoughtfully.
"What if we changed the array to only store the last two Fibonacci numbers instead of all? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursion vs DP
Simple recursion recalculates the same Fibonacci numbers many times, causing slow performance.Step 2: Role of DP in Fibonacci
DP saves previously calculated Fibonacci values in a table (memoization or tabulation), avoiding repeated work.Final Answer:
It stores intermediate results to avoid repeated calculations -> Option AQuick Check:
DP = stores results to save time [OK]
- Thinking DP uses more memory without speed benefit
- Believing DP calculates numbers randomly
- Assuming DP only works for small inputs
Solution
Step 1: Identify Fibonacci base cases
Fibonacci sequence starts with fib(0) = 0 and fib(1) = 1.Step 2: Match initialization with base cases
Array fib[2] = {0, 1} correctly sets fib(0) = 0 and fib(1) = 1.Final Answer:
int fib[2] = {0, 1}; -> Option CQuick Check:
Base fib = 0,1 [OK]
- Swapping the order of 0 and 1
- Setting both base cases to 1
- Initializing both to zero
int fib[6];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i <= 5; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
printf("%d", fib[5]);Solution
Step 1: Calculate Fibonacci values step-by-step
fib[0]=0, fib[1]=1 fib[2]=1, fib[3]=2, fib[4]=3, fib[5]=5Step 2: Identify fib[5]
fib[5] is 5 after the loop completes.Final Answer:
5 -> Option AQuick Check:
fib(5) = 5 [OK]
- Confusing fib(5) with fib(6)
- Starting loop from wrong index
- Off-by-one errors in array indexing
int fib[10];
fib[0] = 0;
fib[1] = 1;
for(int i = 1; i < 10; i++) {
fib[i] = fib[i-1] + fib[i-2];
}Solution
Step 1: Analyze loop start index
The loop starts at i=1, but fib[1] is already initialized, so fib[1] gets overwritten incorrectly.Step 2: Correct loop start
Loop should start at i=2 to use fib[0] and fib[1] for calculation without overwriting base cases.Final Answer:
Change loop to start from i = 2 -> Option BQuick Check:
Loop start = 2 fixes overwrite [OK]
- Starting loop at 1 overwrites fib[1]
- Not initializing base cases properly
- Using wrong loop end condition
Solution
Step 1: Understand space optimization
Only two variables (a, b) track last two Fibonacci numbers; c stores current sum.Step 2: Check loop and updates
Loop from 2 to n, update c = a + b, then shift a = b, b = c correctly to move forward.Final Answer:
Code snippet A correctly implements optimized Fibonacci calculation -> Option DQuick Check:
Two vars + sum update = correct [OK]
- Swapping updates of a and b incorrectly
- Wrong loop range causing off-by-one errors
- Initializing variables incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
