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
Memoization: Cache Function ResultsOriginal Functionfn(a, b) = a + bComputes every timeMemoization WrapperCheck cache firstStore new resultsMemoized FunctionFast cached lookupsAvoids recomputationPerformance ComparisonWithout Memoization:fn(2,3) → compute → 5fn(2,3) → compute → 5 (again!)With Memoization:fn(2,3) → compute → cache → 5fn(2,3) → cache hit → 5 (fast!)🎯 Key Insight: Cache expensive computations using function arguments as keys
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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
24.5K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen