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.

You can assume there are 3 possible input functions: sum, fib, and factorial.

  • sum accepts two integers a and b and returns a + b. Assume that if a value has already been cached for the arguments (b, a) where a != b, it cannot be used for the arguments (a, b). For example, if the arguments are (3, 2) and (2, 3), two separate calls should be made.
  • fib accepts a single integer n and returns 1 if n <= 1 or fib(n - 1) + fib(n - 2) otherwise.
  • factorial accepts a single integer n and returns 1 if n <= 1 or factorial(n - 1) * n otherwise.

Input & Output

Example 1 — Fibonacci Function
$ Input: fn = "fib"
Output: 8
💡 Note: The memoized fibonacci function calculates fib(5). With memoization, fib(1) through fib(5) are calculated only once each, returning 8 efficiently.
Example 2 — Sum Function
$ Input: fn = "sum"
Output: 5
💡 Note: The memoized sum function calculates sum(2, 3) = 5. The result is cached, so subsequent calls with (2, 3) return instantly.
Example 3 — Factorial Function
$ Input: fn = "factorial"
Output: 120
💡 Note: The memoized factorial function calculates factorial(5) = 5! = 120. Each factorial(n) for n=1 to 5 is computed once and cached.

Constraints

  • 1 ≤ function calls ≤ 105
  • 1 ≤ function arguments ≤ 100
  • Functions will be one of: sum, fib, factorial

Visualization

Tap to expand
Memoization Pattern INPUT fn = "fib" Fibonacci Function Function Calls: fib(5) fib(5) Same input called twice! Recursive Tree: 5 4 3 3 2 ALGORITHM STEPS 1 Create Hash Cache cache = {} (empty object) 2 Generate Key key = JSON.stringify(args) 3 Check Cache if (key in cache) return 4 Compute and Store cache[key] = fn(...args) Hash Table State: "[0]" --> 0 "[1]" --> 1 "[2]" --> 1 "[5]" --> 5 FINAL RESULT Output: 8 fib(6) = 8 [OK] Performance Gain: Without Memo O(2^n) With Memo O(n) Second call fib(5): Returns cached: O(1) Key Insight: Memoization uses a hash map to cache function results based on input arguments as keys. When the same inputs occur again, return the cached value instead of recomputing. This transforms exponential recursive algorithms like Fibonacci into linear time complexity. TutorialsPoint - Memoize | Hash Approach
Asked in
Google 25 Facebook 20 Microsoft 15
25.0K Views
Medium Frequency
~15 min Avg. Time
800 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