Memoize - Problem
Given a function fn, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead, it will return a cached value from previous computations, dramatically improving performance for expensive recursive operations.
You can assume there are 3 possible input functions:
sumaccepts two integersaandband returnsa + b. Note that arguments(3, 2)and(2, 3)are considered different and require separate cache entries.fibaccepts a single integernand returns1ifn <= 1orfib(n - 1) + fib(n - 2)otherwise.factorialaccepts a single integernand returns1ifn <= 1orfactorial(n - 1) * notherwise.
Goal: Transform any function into an optimized version that caches results to avoid redundant calculations.
Input & Output
example_1.js โ Sum Function Memoization
$
Input:
fn = sum, calls = [[2,2], [2,2], [1,2]]
โบ
Output:
calls count: 2 (cache hit on second [2,2])
๐ก Note:
The sum function is called with [2,2] twice, but the second call returns the cached result. [1,2] requires a new computation since it's different from [2,2].
example_2.js โ Fibonacci Memoization
$
Input:
fn = fib, calls = [5, 5, 6, 5]
โบ
Output:
calls count: 6 (fib(5) computed once, fib(6) needs fib(5) from cache)
๐ก Note:
fib(5) is computed once and cached. When fib(6) is called, it reuses the cached fib(5) result. The final fib(5) call is a direct cache hit.
example_3.js โ Factorial Edge Case
$
Input:
fn = factorial, calls = [1, 1, 2, 1]
โบ
Output:
calls count: 2 (factorial(1) cached, factorial(2) calls factorial(1))
๐ก Note:
factorial(1) is cached on first call. factorial(2) computes 2 * factorial(1), using the cached value. The final factorial(1) is a cache hit.
Constraints
-
The function will always be one of:
sum,fib, orfactorial -
For
sum: arguments are integers where-100 โค a, b โค 100 -
For
fibandfactorial:0 โค n โค 50 - Arguments order matters: sum(2,3) โ sum(3,2) in cache
- Cache should persist across multiple function calls
Visualization
Tap to expand
Understanding the Visualization
1
Function Call
A function is called with specific arguments
2
Cache Check
Check if this exact computation has been done before
3
Cache Hit/Miss
If found, return cached result. If not, compute and cache the result
4
Performance Gain
Future calls with same arguments return instantly
Key Takeaway
๐ฏ Key Insight: Memoization trades memory space for computational time, transforming exponential algorithms into linear ones by caching results.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code