Fibonacci Using DP in DSA Typescript - Time & Space Complexity
We want to understand how fast the Fibonacci sequence calculation runs when using dynamic programming.
How does the time needed grow as we ask for bigger Fibonacci numbers?
Analyze the time complexity of the following code snippet.
function fibonacciDP(n: number): number {
const dp: number[] = [0, 1];
for (let 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.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calculates each Fibonacci number once.
- How many times: The loop runs from 2 up to n, so about n-1 times.
Each new Fibonacci number is found by adding two previous numbers, done once per step.
| 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 grows.
Time Complexity: O(n)
This means the time needed grows directly in proportion to the size of n.
[X] Wrong: "Calculating Fibonacci with DP is as slow as the simple recursive method because it still calls itself many times."
[OK] Correct: DP stores results and avoids repeated work, so it only does each calculation once, making it much faster.
Understanding this helps you explain how saving past results speeds up problems that repeat work, a key skill in many coding challenges.
"What if we changed the DP array to only keep the last two Fibonacci numbers instead of all? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursive Fibonacci calculation
Simple recursion recalculates the same Fibonacci numbers many times, causing inefficiency.Step 2: Understand DP optimization
DP stores previously calculated Fibonacci numbers in a table (memoization or tabulation) to avoid repeated work.Final Answer:
It avoids repeated calculations by storing intermediate results. -> Option BQuick Check:
DP = stores results to save time [OK]
- Thinking DP uses less memory than recursion
- Believing DP calculates randomly
- Assuming DP only works for small inputs
Solution
Step 1: Check array size and initialization
We need an array of size n+1 to store Fibonacci numbers from 0 to n. Filling with 0 and setting dp[1] = 1 is correct.Step 2: Validate each option
const dp: number[] = new Array(n + 1).fill(0); dp[1] = 1; correctly creates dp with size n+1, fills with 0, and sets dp[1] = 1. Others have wrong sizes or initial values.Final Answer:
const dp: number[] = new Array(n + 1).fill(0); dp[1] = 1; -> Option AQuick Check:
Array size = n+1, dp[1] = 1 [OK]
- Using array size n instead of n+1
- Initializing dp[0] or dp[1] incorrectly
- Leaving dp array uninitialized
function fib(n: number): number {
const dp: number[] = new Array(n + 1).fill(0);
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
console.log(fib(5));Solution
Step 1: Trace DP array values for n=5
dp[0]=0, dp[1]=1; then dp[2]=1, dp[3]=2, dp[4]=3, dp[5]=5.Step 2: Return dp[5]
The function returns dp[5] which is 5.Final Answer:
5 -> Option DQuick Check:
Fibonacci(5) = 5 [OK]
- Confusing index starting point
- Returning dp[n-1] instead of dp[n]
- Miscomputing dp values in loop
function fib(n: number): number {
const dp: number[] = new Array(n).fill(0);
dp[0] = 0;
dp[1] = 1;
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}Solution
Step 1: Analyze array size and access
Array dp has size n, but loop accesses dp[n] beyond the initial length.Step 2: Fix array size
Increase dp size to n+1 to safely access dp[n].Final Answer:
Change array size to n+1 to avoid out-of-bounds error. -> Option AQuick Check:
Array size must cover dp[n] [OK]
- Ignoring array size mismatch
- Starting loop incorrectly
- Unnecessary dp initialization changes
Solution
Step 1: Understand space usage in DP Fibonacci
DP uses an array of size n+1, so space is O(n).Step 2: Optimize space by storing only needed values
Since each Fibonacci number depends only on the previous two, storing just two variables suffices.Step 3: Compare options
Use two variables to store only the last two Fibonacci numbers instead of an array. uses two variables, reducing space to O(1). Others do not reduce space or are inefficient.Final Answer:
Use two variables to store only the last two Fibonacci numbers instead of an array. -> Option CQuick Check:
Two vars = O(1) space [OK]
- Using recursion without memoization increases time
- Storing all numbers globally wastes space
- Filling full dp array every call wastes memory
Ready to prove it?
Pass the test and this pattern moves unknown
