Skip to content

Commit 2487ec2

Browse files
committed
Add solution #2622
1 parent 9cae69f commit 2487ec2

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@
365365
2619|[Array Prototype Last](./2619-array-prototype-last.js)|Easy|
366366
2620|[Counter](./2620-counter.js)|Easy|
367367
2621|[Sleep](./2621-sleep.js)|Easy|
368+
2622|[Cache With Time Limit](./2622-cache-with-time-limit.js)|Medium|
368369
2629|[Function Composition](./2629-function-composition.js)|Easy|
369370
3392|[Count Subarrays of Length Three With a Condition](./3392-count-subarrays-of-length-three-with-a-condition.js)|Easy|
370371
3396|[Minimum Number of Operations to Make Elements in Array Distinct](./3396-minimum-number-of-operations-to-make-elements-in-array-distinct.js)|Easy|
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 2622. Cache With Time Limit
3+
* https://leetcode.com/problems/cache-with-time-limit/
4+
* Difficulty: Medium
5+
*
6+
* Write a class that allows getting and setting key-value pairs, however a time until
7+
* expiration is associated with each key.
8+
*
9+
* The class has three public methods:
10+
* - set(key, value, duration): accepts an integer key, an integer value, and a duration
11+
* in milliseconds. Once the duration has elapsed, the key should be inaccessible.
12+
* The method should return true if the same un-expired key already exists and false
13+
* otherwise. Both the value and duration should be overwritten if the key already exists.
14+
*
15+
* - get(key): if an un-expired key exists, it should return the associated value.
16+
* Otherwise it should return -1.
17+
*
18+
* - count(): returns the count of un-expired keys.
19+
*/
20+
21+
var TimeLimitedCache = function() {
22+
this.cache = new Map();
23+
};
24+
25+
/**
26+
* @param {number} key
27+
* @param {number} value
28+
* @param {number} duration time until expiration in ms
29+
* @return {boolean} if un-expired key already existed
30+
*/
31+
TimeLimitedCache.prototype.set = function(key, value, duration) {
32+
const hit = this.cache.has(key) && this.cache.get(key)[1] > Date.now();
33+
this.cache.set(key, [value, Date.now() + duration]);
34+
return hit;
35+
};
36+
37+
/**
38+
* @param {number} key
39+
* @return {number} value associated with key
40+
*/
41+
TimeLimitedCache.prototype.get = function(key) {
42+
if (!this.cache.has(key)) return -1;
43+
const [value, expiredAt] = this.cache.get(key);
44+
return expiredAt > Date.now() ? value : -1;
45+
};
46+
47+
/**
48+
* @return {number} count of non-expired keys
49+
*/
50+
TimeLimitedCache.prototype.count = function() {
51+
return [...this.cache.keys()].reduce((count, key) => {
52+
return this.cache.get(key)[1] > Date.now() ? ++count : count;
53+
}, 0);
54+
};

0 commit comments

Comments
 (0)