Memoize II Problem
Description
LeetCode Problem 2630.
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.
fn 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.
Example 1:
Input:
getInputs = () => [[2,2],[2,2],[1,2]]
fn = function (a, b) { return a + b; }
Output: [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}]
Explanation:
const inputs = getInputs();
const memoized = memoize(fn);
for (const arr of inputs) {
memoized(...arr);
}
For the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn().
For the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required.
For the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2.
Example 2:
Input:
getInputs = () => [[{},{}],[{},{}],[{},{}]]
fn = function (a, b) { return ({...a, ...b}); }
Output: [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}]
Explanation:
Merging 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.
Example 3:
Input:
getInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; }
fn = function (a, b) { return ({...a, ...b}); }
Output: [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}]
Explanation:
Merging 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.
Constraints:
1 <= inputs.length <= 10^50 <= inputs.flat().length <= 10^5inputs[i][j] != NaN
Solution
Approach: Trie of Maps keyed by each argument
Here arguments can be any value and are compared with ===, so turning them into a string (as in the first Memoize) is wrong: two different {} objects must be different keys, and 1 and "1" must differ too.
Use a trie. Each node has a Map from one argument value to a child node, plus a slot for a stored result. A call walks one level per argument, creating missing nodes, and the node reached at the end of the argument list is where the result for that exact list is cached. A Map compares keys by identity for objects and by value for primitives, which is the === behaviour we need (and the statement rules out NaN).
Storing the result in the node, with a separate has flag, keeps the zero-argument call (the root node) and calls whose result is undefined correct. Arguments of different lengths never clash, since f(1) ends at a different node than f(1, 2).
Complexity: O(k) per call for k arguments; memory is proportional to the total length of all distinct argument lists.
/**
* @param {Function} fn
* @return {Function}
*/
function memoize(fn) {
const makeNode = () => ({ children: new Map(), hasValue: false, value: undefined });
const root = makeNode();
return function (...args) {
let node = root;
for (const arg of args) {
let next = node.children.get(arg);
if (next === undefined) {
next = makeNode();
node.children.set(arg, next);
}
node = next;
}
if (!node.hasValue) {
node.value = fn(...args);
node.hasValue = true;
}
return node.value;
};
}