Memoization to Optimize Recursion in DSA Javascript - Time & Space Complexity
We want to see how using memoization changes the speed of recursive functions.
How does remembering past answers help us do less work?
Analyze the time complexity of the following memoized Fibonacci function.
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
This function calculates Fibonacci numbers using recursion and stores results to avoid repeated work.
Look for repeated calls and stored results.
- Primary operation: Recursive calls to fib with smaller n.
- How many times: Each unique n is computed once, then reused from memo.
Each number from 0 up to n is calculated once, then reused.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calculations |
| 100 | About 100 calculations |
| 1000 | About 1000 calculations |
Pattern observation: The work grows roughly in a straight line as n grows.
Time Complexity: O(n)
This means the function does work proportional to the input size, not more.
[X] Wrong: "Memoization makes recursion instantly fast for all problems."
[OK] Correct: Memoization only helps if the problem has overlapping subproblems; otherwise, it won't reduce repeated work.
Understanding memoization shows you can improve slow recursive solutions by saving past results, a key skill in coding challenges.
"What if we removed memoization? How would the time complexity change?"
Practice
memoization in recursive functions?Solution
Step 1: Understand what memoization does
Memoization saves the results of function calls so that if the same inputs occur again, the saved result is used instead of recalculating.Step 2: Identify the effect on recursion
This reduces repeated work and speeds up recursive functions by avoiding duplicate calculations.Final Answer:
To store results of expensive function calls and reuse them later -> Option BQuick Check:
Memoization = Store and reuse results [OK]
- Thinking memoization makes recursion slower
- Confusing memoization with iteration
- Believing memoization removes recursion
Solution
Step 1: Understand memo object usage
The memo object should be an object or map to store key-value pairs of inputs and results.Step 2: Correct placement and passing
Declaringconst memo = {}inside the function and passing it as a parameter ensures the same memo is used across recursive calls.Final Answer:
const memo = {}; inside the function, then pass it as a parameter -> Option AQuick Check:
Memo object declared and passed = const memo = {}; inside the function, then pass it as a parameter [OK]
- Using array instead of object for memo
- Not passing memo to recursive calls
- Declaring memo as a number
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
console.log(fib(5));Solution
Step 1: Understand Fibonacci calculation with memoization
fib(5) calculates Fibonacci number at position 5 using memo to avoid repeated calls.Step 2: Calculate fib(5) step-by-step
fib(0)=0, fib(1)=1, fib(2)=1, fib(3)=2, fib(4)=3, fib(5)=5.Final Answer:
5 -> Option AQuick Check:
fib(5) = 5 [OK]
- Confusing fib(5) with fib(6)
- Ignoring memo and recalculating
- Assuming output is 8
function factorial(n, memo = {}) {
if (n === 0) return 1;
if (memo[n]) return memo[n];
memo[n] = n * factorial(n - 1);
return memo[n];
}Solution
Step 1: Check recursive call parameters
The recursive call to factorial misses passing the memo object, so memo is reset each time.Step 2: Fix by passing memo in recursion
Change call to factorial(n - 1, memo) to keep memo consistent across calls.Final Answer:
Pass memo in recursive call: factorial(n - 1, memo) -> Option CQuick Check:
Pass memo to recursive calls to fix [OK]
- Forgetting to pass memo in recursion
- Changing base case unnecessarily
- Removing memo defeats optimization
n stairs taking 1 or 2 steps at a time. Which memoization approach below correctly improves performance?Solution
Step 1: Understand the problem and recursion
The function counts ways to climb stairs by summing ways(n-1) and ways(n-2).Step 2: Apply memoization correctly
Passing a memo object through recursive calls stores results for each stair number, avoiding repeated calculations.Step 3: Evaluate other options
Global counters don't store results, loops change approach, and storing only even results misses odd cases.Final Answer:
Use a memo object passed through recursive calls to store results for each stair number -> Option DQuick Check:
Memo object for all inputs optimizes recursion [OK]
- Not passing memo object through recursion
- Partial memoization missing some inputs
- Confusing memoization with iteration
Ready to prove it?
Pass the test and this pattern moves unknown
