TobilobaCodes – LeetCode Explorer

2623. Memoize

On this page, we explore LeetCode Problem 2623: Memoize. This problem challenges you to return a memoized version of a given function, caching its output based on input arguments.

📄 Problem Statement

Given a function fn, return a memoized version of that function. A memoized function is one that stores the result of previous calls and returns the cached result when called with the same inputs again.

Assume three possible input functions: sum, fib, and factorial. The inputs are strictly ordered: (2,3) and (3,2) are treated as different.

💡 Example

Input:
const memoized = memoize((a, b) => a + b);
memoized(2, 3); // 5
memoized(2, 3); // 5 (from cache)
memoized(3, 2); // 5 (new call)

🧠 Explanation

We use the rest parameter ...args to capture all input arguments. Then, we create a unique string key using JSON.stringify(args) and store it in a Map.

When the function is called, we check if the key exists in the cache. If so, return the cached value; if not, compute the result, store it, and return it.

✅ Your Solution


/**
 * @param {Function} fn
 * @return {Function}
 */
function memoize(fn) {
    const cache = new Map();

    return function(...args) {
        const key = JSON.stringify(args);
        if (cache.has(key)) {
            return cache.get(key);
        }
        const result = fn(...args);
        cache.set(key, result);
        return result;
    }
}