Cache With Time Limit
Problem
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.
Examples
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
Method 1 – Hash Map with Expiry Tracking
Intuition
We use a hash map to store each key's value and its expiry timestamp. When setting a key, we update its value and expiry. When getting a key or counting, we check if the key is expired and remove it if so. This ensures all operations are efficient and expired keys are not accessible.
Approach
- Use a hash map to store key → { value, expiry }.
- For
set(key, value, duration), check if the key exists and is not expired:- If so, return true; otherwise, return false.
- Update the value and expiry to now + duration.
- For
get(key), check if the key exists and is not expired:- If so, return the value.
- If expired, remove it and return -1.
- For
count(), iterate through all keys and count those not expired, removing expired ones.
Code
JavaScript
class TimeLimitedCache {
constructor() {
this.map = new Map();
}
set(key, value, duration) {
const now = Date.now();
const exists = this.map.has(key) && this.map.get(key).expiry > now;
this.map.set(key, { value, expiry: now + duration });
return exists;
}
get(key) {
const now = Date.now();
if (!this.map.has(key)) return -1;
const { value, expiry } = this.map.get(key);
if (expiry > now) return value;
this.map.delete(key);
return -1;
}
count() {
const now = Date.now();
let ans = 0;
for (const [k, { expiry }] of this.map) {
if (expiry > now) ans++;
else this.map.delete(k);
}
return ans;
}
}
TypeScript
class TimeLimitedCache {
private map: Map<number, { value: number; expiry: number }> = new Map();
set(key: number, value: number, duration: number): boolean {
const now = Date.now();
const exists = this.map.has(key) && this.map.get(key)!.expiry > now;
this.map.set(key, { value, expiry: now + duration });
return exists;
}
get(key: number): number {
const now = Date.now();
if (!this.map.has(key)) return -1;
const { value, expiry } = this.map.get(key)!;
if (expiry > now) return value;
this.map.delete(key);
return -1;
}
count(): number {
const now = Date.now();
let ans = 0;
for (const [k, { expiry }] of this.map) {
if (expiry > now) ans++;
else this.map.delete(k);
}
return ans;
}
}
Complexity
- ⏰ Time complexity: O(1) for set and get, O(n) for count (where n is the number of keys in the cache)
- 🧺 Space complexity: O(n)