Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 3bf762c

Browse files
committedJan 4, 2025
Add solution #2630
1 parent 7edb7e3 commit 3bf762c

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,7 @@
370370
2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium|
371371
2623|[Memoize](./2623-memoize.js)|Medium|
372372
2629|[Function Composition](./2629-function-composition.js)|Easy|
373+
2630|[Memoize II](./2630-memoize-ii.js)|Hard|
373374
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
374375
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
375376
3397|[Maximum Number of Distinct Elements After Operations](./3397-maximum-number-of-distinct-elements-after-operations.js)|Medium|

‎solutions/2630-memoize-ii.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* 2630. Memoize II
3+
* https://leetcode.com/problems/memoize-ii/
4+
* Difficulty: Hard
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+
* fn can be any function and there are no constraints on what type
12+
* of values it accepts. Inputs are considered identical if they
13+
* are === to each other.
14+
*/
15+
16+
/**
17+
* @param {Function} fn
18+
* @return {Function}
19+
*/
20+
function memoize(fn) {
21+
const cache = {};
22+
const idLookup = new Map();
23+
function generateId(item) {
24+
return idLookup.get(item) ?? idLookup.set(item, idLookup.size + 1).get(item);
25+
}
26+
return (...args) => {
27+
const key = args.map(generateId).join('-');
28+
return !cache.hasOwnProperty(key) ? (cache[key] = fn(...args)) : cache[key];
29+
};
30+
}

0 commit comments

Comments
 (0)
Please sign in to comment.