{ "data": { "question": { "questionId": "2744", "questionFrontendId": "2630", "boundTopicId": null, "title": "Memoize II", "titleSlug": "memoize-ii", "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 return a cached value.
\n\nfn
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.
\n
Example 1:
\n\n\nInput: \ngetInputs = () => [[2,2],[2,2],[1,2]]\nfn = function (a, b) { return a + b; }\nOutput: [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}]\nExplanation:\nconst inputs = getInputs();\nconst memoized = memoize(fn);\nfor (const arr of inputs) {\n memoized(...arr);\n}\n\nFor the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn().\nFor the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required.\nFor the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2.\n\n\n
Example 2:
\n\n\nInput: \ngetInputs = () => [[{},{}],[{},{}],[{},{}]] \nfn = function (a, b) { return ({...a, ...b}); }\nOutput: [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}]\nExplanation:\nMerging two empty objects will always result in an empty object. It may seem like there should only be 1 call to fn() because of cache-hits, however none of those objects are === to each other.\n\n\n
Example 3:
\n\n\nInput: \ngetInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; }\nfn = function (a, b) { return ({...a, ...b}); }\nOutput: [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}]\nExplanation:\nMerging two empty objects will always result in an empty object. The 2nd and 3rd third function calls result in a cache-hit. This is because every object passed in is identical.\n\n\n
\n
Constraints:
\n\n1 <= inputs.length <= 105
0 <= inputs.flat().length <= 105
inputs[i][j] != NaN
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 5.1.6, Node.js 16.13.2
.
Your code is run with --harmony
flag, enabling new ES2022 features.
lodash.js library is included by default.
\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }