{ "data": { "question": { "questionId": "2731", "questionFrontendId": "2623", "boundTopicId": null, "title": "Memoize", "titleSlug": "memoize", "content": "
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 returned a cached value.
\n\nYou can assume there are 3 possible input functions: sum
, fib
, and factorial
.
sum
accepts two integers a
and b
and returns a + b
.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.\n
Example 1:
\n\n\nInput\n"sum"\n["call","call","getCallCount","call","getCallCount"]\n[[2,2],[2,2],[],[1,2],[]]\nOutput\n[4,4,1,3,2]\n\nExplanation\nconst sum = (a, b) => a + b;\nconst memoizedSum = memoize(sum);\nmemoizedSum(2, 2); // Returns 4. sum() was called as (2, 2) was not seen before.\nmemoizedSum(2, 2); // Returns 4. However sum() was not called because the same inputs were seen before.\n// Total call count: 1\nmemoizedSum(1, 2); // Returns 3. sum() was called as (1, 2) was not seen before.\n// Total call count: 2\n\n\n
Example 2:
\n\n\nInput\n"factorial"\n["call","call","call","getCallCount","call","getCallCount"]\n[[2],[3],[2],[],[3],[]]\nOutput\n[2,6,2,2,6,2]\n\nExplanation\nconst factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));\nconst memoFactorial = memoize(factorial);\nmemoFactorial(2); // Returns 2.\nmemoFactorial(3); // Returns 6.\nmemoFactorial(2); // Returns 2. However factorial was not called because 2 was seen before.\n// Total call count: 2\nmemoFactorial(3); // Returns 6. However factorial was not called because 3 was seen before.\n// Total call count: 2\n\n\n
Example 3:
\n\n\nInput\n"fib"\n["call","getCallCount"]\n[[5],[]]\nOutput\n[8,1]\n\nExplanation\nfib(5) = 8\n// Total call count: 1\n\n\n\n
\n
Constraints:
\n\n0 <= a, b <= 105
1 <= n <= 10
at most 105 function calls
at most 105 attempts to access callCount
input function is sum, fib, or factorial
Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES6 features.
lodash.js library is included by default.
\\r\\n\\r\\nFor Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.
\"], \"typescript\": [\"Typescript\", \"TypeScript 4.5.4, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2020 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }