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 gets bigger.
Analyze the time complexity of the following code snippet.
public int Fibonacci(int n) {
int[] dp = new int[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 building up from smaller results and storing them 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 (from 2 up to n).
As n grows, the number of steps grows roughly the same as n because each Fibonacci number is calculated once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 9 steps |
| 100 | About 99 steps |
| 1000 | About 999 steps |
Pattern observation: The steps increase linearly as input size increases.
Time Complexity: O(n)
This means the time to compute grows in a straight line with the input size.
[X] Wrong: "Calculating Fibonacci with DP is still slow because it uses recursion like the naive method."
[OK] Correct: This code uses a loop and stores results, so it avoids repeated calculations and runs much faster than naive recursion.
Understanding this approach shows you can improve slow recursive solutions by saving work, a key skill in many coding problems.
"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 inefficiency
Simple recursion recalculates the same Fibonacci numbers many times, causing exponential time complexity.Step 2: Role of Dynamic Programming
DP stores previously calculated Fibonacci numbers in a table (memoization or tabulation), so each number is computed once.Final Answer:
It stores intermediate results to avoid repeated calculations -> Option CQuick Check:
DP avoids repeated work = C [OK]
- Thinking DP uses less memory than recursion
- Believing DP calculates numbers randomly
- Assuming DP only works for small inputs
Solution
Step 1: Array size for DP
We need an array of size n+1 to store Fibonacci numbers from 0 to n.Step 2: Initial values for Fibonacci
Fibonacci sequence starts with dp[0] = 0 and dp[1] = 1.Final Answer:
int[] dp = new int[n + 1]; dp[0] = 0; dp[1] = 1; -> Option AQuick Check:
Correct size and base values = A [OK]
- Using array size n instead of n+1
- Swapping dp[0] and dp[1] values
- Starting dp[0] or dp[1] with wrong numbers
int n = 5;
int[] dp = new int[n + 1];
dp[0] = 0; dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
Console.WriteLine(dp[n]);Solution
Step 1: Calculate Fibonacci values up to n=5
dp[0]=0, dp[1]=1 Then dp[2]=1, dp[3]=2, dp[4]=3, dp[5]=5.Step 2: Output dp[5]
The code prints dp[5], which is 5.Final Answer:
5 -> Option DQuick Check:
Fibonacci(5) = 5 [OK]
- Confusing Fibonacci index starting at 0 or 1
- Calculating dp[5] as 8 or 13 incorrectly
- Off-by-one errors in loop
int n = 6;
int[] dp = new int[n];
dp[0] = 0; dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
Console.WriteLine(dp[n]);Solution
Step 1: Check array size and indexing
Array dp has size n=6, valid indices 0 to 5. Loop runs i=2 to 6 inclusive, accessing dp[6] which is out of bounds.Step 2: Resulting error
Accessing dp[6] causes IndexOutOfRangeException at runtime.Final Answer:
Array size is too small causing IndexOutOfRangeException -> Option AQuick Check:
Array size < loop max index = error [OK]
- Using array size n instead of n+1
- Ignoring loop boundary causing runtime error
- Assuming code runs without error
Solution
Step 1: Understand space optimization
We only need last two Fibonacci numbers to compute the next, so store them in variables a and b.Step 2: Analyze the correct code logic
int a = 0, b = 1, c = 0; for (int i = 2; i <= 10; i++) { c = a + b; a = b; b = c; } Console.WriteLine(c); correctly updates a and b in each iteration and stores current Fibonacci in c, printing c after loop.Step 3: Check other options
int[] dp = new int[10]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= 10; i++) dp[i] = dp[i - 1] + dp[i - 2]; Console.WriteLine(dp[10]); uses array (not O(1) space), the code with loop i < 10 updates variables incorrectly, the code with fib += i sums numbers instead of Fibonacci.Final Answer:
int a = 0, b = 1, c = 0; for (int i = 2; i <= 10; i++) { c = a + b; a = b; b = c; } Console.WriteLine(c); -> Option BQuick Check:
Use two vars to save space = B [OK]
- Using full array instead of variables
- Incorrect variable updates causing wrong output
- Summing indices instead of Fibonacci numbers
Ready to prove it?
Pass the test and this pattern moves unknown
