Skip to content

Practice Memoize

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#2623
LeetCode Problem

Memoize

Problem Statement

Return a wrapper for fn that caches results by the full ordered argument tuple, so repeated identical arguments do not call fn again. The possible functions are sum(a,b) = a + b; fib(n), equal to 1 for n <= 1 and otherwise fib(n-1) + fib(n-2); and factorial(n), equal to 1 for n <= 1 and otherwise n * factorial(n-1). For sum, (a,b) and (b,a) are separate cache keys when a differs from b.

Source: Memoize on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
fnName = "sum" actions = ["call","call","getCallCount","call","getCallCount"] values = [[2,2],[2,2],[],[1,2],[]]
Output
[4,4,1,3,2]

# Example 2

Input
fnName = "factorial" actions = ["call","call","call","getCallCount","call","getCallCount"] values = [[2],[3],[2],[],[3],[]]
Output
[2,6,2,2,6,2]

# Example 3

Input
fnName = "fib" actions = ["call","getCallCount"] values = [[5],[]]
Output
[8,1]

Constraints

0 <= a, b <= 10^5
1 <= n <= 10
1 <= actions.length <= 10^5
actions.length === values.length
actions[i] is one of "call" and "getCallCount"
fnName is one of "sum", "factorial" and "fib"

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.