Memoize II - 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.
The function fn can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are === to each other.
Input & Output
Example 1 — Basic Function Memoization
$
Input:
fn = (a, b) => a + b
›
Output:
memoized function that caches results
💡 Note:
First call fn(2,3) computes 5 and caches it. Second call fn(2,3) returns cached 5 without computation.
Example 2 — Factorial Memoization
$
Input:
fn = (n) => n <= 1 ? 1 : n * fn(n-1)
›
Output:
memoized factorial function
💡 Note:
Recursive calls get memoized. factorial(5) caches results for 1,2,3,4,5. Later calls reuse cached values.
Example 3 — Object Arguments
$
Input:
fn = (obj) => obj.x + obj.y
›
Output:
memoized function handling objects
💡 Note:
Same object reference returns cached result. Different objects with same values are treated as different inputs.
Constraints
- 1 ≤ inputs.length ≤ 105
- 0 ≤ inputs.flat().length ≤ 105
- inputs[i][j] != NaN
Visualization
Tap to expand
Understanding the Visualization
1
Input
Original function that may be expensive to compute
2
Process
Wrap with caching mechanism that stores results
3
Output
Memoized function that avoids redundant computations
Key Takeaway
🎯 Key Insight: Cache function results by using arguments as keys to avoid redundant computations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code