Skip to content

Commit 7edb7e3

Browse files
committed
Add solution #2623
1 parent 4089031 commit 7edb7e3

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,7 @@
368368
2620|[Counter](./2620-counter.js)|Easy|
369369
2621|[Sleep](./2621-sleep.js)|Easy|
370370
2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium|
371+
2623|[Memoize](./2623-memoize.js)|Medium|
371372
2629|[Function Composition](./2629-function-composition.js)|Easy|
372373
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
373374
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|

solutions/2623-memoize.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 2623. Memoize
3+
* https://leetcode.com/problems/memoize/
4+
* Difficulty: Medium
5+
*
6+
* Given a function fn, return a memoized version of that function.
7+
*
8+
* A memoized function is a function that will never be called twice
9+
* with the same inputs. Instead it will return a cached value.
10+
*
11+
* You can assume there are 3 possible input functions: sum, fib,
12+
* and factorial.
13+
*
14+
* - `sum` accepts two integers a and b and returns a + b. Assume that
15+
* if a value has already been cached for the arguments (b, a) where
16+
* a != b, it cannot be used for the arguments (a, b). For example,
17+
* if the arguments are (3, 2) and (2, 3), two separate calls should
18+
* be made.
19+
* - `fib` accepts a single integer n and returns 1 if n <= 1 or
20+
* fib(n - 1) + fib(n - 2) otherwise.
21+
* - `factorial` accepts a single integer n and returns 1 if n <= 1 or
22+
* factorial(n - 1) * n otherwise.
23+
*/
24+
25+
/**
26+
* @param {Function} fn
27+
* @return {Function}
28+
*/
29+
function memoize(fn) {
30+
const cache = new Map();
31+
32+
return (...args) => {
33+
const key = String(args);
34+
if (cache.has(key)) {
35+
return cache.get(key);
36+
}
37+
const value = fn(...args);
38+
cache.set(key, value);
39+
return value;
40+
};
41+
}

0 commit comments

Comments
 (0)