
Problem
Solution
Submissions
Basic Memoization
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 8
Write a JavaScript program to implement basic memoization for a function that calculates the nth Fibonacci number. Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. This significantly improves performance for recursive functions with overlapping subproblems.
Example 1
- Input: n = 10
- Output: 55
- Explanation:
- Calculate Fibonacci(10) using memoization.
- Store intermediate results: F(0)=0, F(1)=1, F(2)=1, F(3)=2, F(4)=3, F(5)=5.
- Continue storing: F(6)=8, F(7)=13, F(8)=21, F(9)=34.
- Finally calculate F(10) = F(9) + F(8) = 34 + 21 = 55.
- Return 55 as the result, with all intermediate values cached.
- Calculate Fibonacci(10) using memoization.
Example 2
- Input: n = 6
- Output: 8
- Explanation:
- Start calculating Fibonacci(6) with empty cache.
- Build up cache with base cases: F(0)=0, F(1)=1.
- Calculate and cache: F(2)=1, F(3)=2, F(4)=3, F(5)=5.
- Finally compute F(6) = F(5) + F(4) = 5 + 3 = 8.
- Return 8, with cache containing all values from F(0) to F(6).
- Start calculating Fibonacci(6) with empty cache.
Constraints
- 0 ≤ n ≤ 50
- The function should use memoization to optimize performance
- Cache should store previously calculated results
- Time Complexity: O(n) with memoization (vs O(2^n) without)
- Space Complexity: O(n) for the cache storage
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Create a cache object or Map to store previously calculated results
- Check if the result for the current input already exists in the cache
- If cached result exists, return it immediately without recalculation
- If not cached, calculate the result recursively
- Store the calculated result in the cache before returning
- Use the standard Fibonacci recurrence relation: F(n) = F(n-1) + F(n-2)
- Handle base cases F(0) = 0 and F(1) = 1