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
Memoize II - Map with Argument-based Keys INPUT fn = (a, b) => a + b Original Function Function Calls: memoFn(2, 3) memoFn(2, 3) same! memoFn(1, 4) Identity Check (===) 2 === 2 // true {} === {} // false Objects need same reference ALGORITHM STEPS 1 Create Cache Map Map() for storing results 2 Build Nested Maps Each arg creates a level 3 Check Cache Use === for key lookup 4 Compute or Return Cache miss: call fn() Cache Structure (Nested Map) root 2 1 3: 5 4: 5 FINAL RESULT Memoized Function memoFn(2, 3) --> 5 (computed once) Execution Log: memoFn(2,3) MISS - computed: 5 fn called memoFn(2,3) HIT - cached: 5 OK memoFn(1,4) MISS - computed: 5 fn called Performance Gain 3 calls, only 2 computations Duplicate call returned from cache Key Insight: Nested Maps preserve object identity (===) for each argument position. Unlike string keys, Map keys can be any value and use reference equality. This allows memoizing functions with object arguments where same reference returns cached result, different references recompute. TutorialsPoint - Memoize II | Map with Argument-based Keys Approach
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