2623. Memoize
Description
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Βaandband returnsa + b.Β Assume that if a value has already been cached for the arguments(b, a)wherea != 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ΒnandΒ returnsΒ1ifn <= 1orΒfib(n - 1) + fib(n - 2)Β otherwise.factorialΒ accepts a single integerΒnand returns1Β ifΒn <= 1Β orΒfactorial(n - 1) * nΒ otherwise.
Β
Example 1:
Input: fnName = "sum" actions = ["call","call","getCallCount","call","getCallCount"] values = [[2,2],[2,2],[],[1,2],[]] Output: [4,4,1,3,2] Explanation: const sum = (a, b) => a + b; const memoizedSum = memoize(sum); memoizedSum(2, 2); // "call" - returns 4. sum() was called as (2, 2) was not seen before. memoizedSum(2, 2); // "call" - returns 4. However sum() was not called because the same inputs were seen before. // "getCallCount" - total call count: 1 memoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before. // "getCallCount" - total call count: 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] Explanation: const factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1)); const memoFactorial = memoize(factorial); memoFactorial(2); // "call" - returns 2. memoFactorial(3); // "call" - returns 6. memoFactorial(2); // "call" - returns 2. However factorial was not called because 2 was seen before. // "getCallCount" - total call count: 2 memoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before. // "getCallCount" - total call count: 2
Example 3:
Input: fnName = "fib" actions = ["call","getCallCount"] values = [[5],[]] Output: [8,1] Explanation: fib(5) = 8 // "call" // "getCallCount" - total call count: 1
Β
Constraints:
0 <= a, b <= 1051 <= n <= 101 <= actions.length <= 105actions.length === values.lengthactions[i]is one of "call" and "getCallCount"fnNameis one of "sum", "factorial" andΒ "fib"
Solutions
Solution 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |