Cache With Time Limit Problem
Description
LeetCode Problem 2622.
Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.
The class has three public methods:
set(key, value, duration): accepts an integer key, an integer value, and a duration in milliseconds. Once the duration has elapsed, the key should be inaccessible. The method should return true if the same un-expired key already exists and false otherwise. Both the value and duration should be overwritten if the key already exists.
get(key): if an un-expired key exists, it should return the associated value. Otherwise it should return -1.
count(): returns the count of un-expired keys.
Example 1:
Input:
actions = ["TimeLimitedCache", "set", "get", "count", "get"]
values = [[], [1, 42, 100], [1], [], [1]]
timeDelays = [0, 0, 50, 50, 150]
Output: [null, false, 42, 1, -1]
Explanation:
At t=0, the cache is constructed.
At t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned.
At t=50, key=1 is requested and the value of 42 is returned.
At t=50, count() is called and there is one active key in the cache.
At t=100, key=1 expires.
At t=150, get(1) is called but -1 is returned because the cache is empty.
Example 2:
Input:
actions = ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"]
values = [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []]
timeDelays = [0, 0, 40, 50, 120, 200, 250]
Output: [null, false, true, 50, 50, -1, 0]
Explanation:
At t=0, the cache is constructed.
At t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned.
At t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten.
At t=50, get(1) is called which returned 50.
At t=120, get(1) is called which returned 50.
At t=140, key=1 expires.
At t=200, get(1) is called but the cache is empty so -1 is returned.
At t=250, count() returns 0 because the cache is empty.
Constraints:
0 <= key, value <= 10^90 <= duration <= 10001 <= actions.length <= 100actions.length === values.lengthactions.length === timeDelays.length0 <= timeDelays[i] <= 1450actions[i]is one of "TimeLimitedCache", "set", "get" and "count"- First action is always "TimeLimitedCache" and must be executed immediately, with a 0-millisecond delay
Solution
Approach: Store an expiry time per key
Instead of running timers, store for every key its value and the time it expires (Date.now() + duration), and compare with the current time whenever the key is read.
setchecks whether the key exists and is still alive, then overwrites both value and expiry (the new duration replaces the old one) and returns whether it was alive.getreturns the value only if the entry exists and its expiry is still in the future, otherwise-1.countwalks the map, counts live entries and deletes the expired ones on the way, so the map does not grow forever.
An entry counts as expired once expiresAt <= now, so a duration of 0 makes the key unreadable immediately. Checking the clock lazily avoids having to cancel timers when a key is overwritten.
Complexity: set and get are O(1); count is O(n) in the number of stored keys. Space is O(n).
class TimeLimitedCache {
constructor() {
this.store = new Map(); // key -> { value, expiresAt }
}
/**
* @param {number} key
* @param {number} value
* @param {number} duration time until expiration in ms
* @return {boolean} if un-expired key already existed
*/
set(key, value, duration) {
const now = Date.now();
const entry = this.store.get(key);
const alive = entry !== undefined && entry.expiresAt > now;
this.store.set(key, { value, expiresAt: now + duration });
return alive;
}
/**
* @param {number} key
* @return {number} value associated with key
*/
get(key) {
const entry = this.store.get(key);
return entry !== undefined && entry.expiresAt > Date.now() ? entry.value : -1;
}
/**
* @return {number} count of non-expired keys
*/
count() {
const now = Date.now();
let live = 0;
for (const [key, entry] of this.store) {
if (entry.expiresAt > now) live++;
else this.store.delete(key);
}
return live;
}
}