Cache With Time Limit - Problem
Design and implement a time-based cache that automatically expires keys after a specified duration. This cache supports the typical get and set operations but with a twist - each key has an associated time-to-live (TTL).
Your TimeLimitedCache class should implement these three methods:
set(key, value, duration): Stores an integer key with an integer value that expires afterdurationmilliseconds. Returnstrueif an unexpired key already exists (and overwrites it),falseotherwise.get(key): Returns the value associated with the key if it exists and hasn't expired, otherwise returns-1.count(): Returns the number of unexpired keys currently in the cache.
This type of cache is commonly used in web applications for session management, API rate limiting, and temporary data storage where automatic cleanup is essential for performance.
Input & Output
example_1.js โ Basic Operations
$
Input:
const cache = new TimeLimitedCache();
cache.set(1, 42, 1000); // key=1, value=42, duration=1000ms
cache.get(1); // immediately after
cache.count(); // count unexpired keys
โบ
Output:
false (no existing key)
42 (value retrieved)
1 (one unexpired key)
๐ก Note:
First set() returns false since key 1 didn't exist. get() returns 42 since the key hasn't expired yet. count() returns 1 since there's one active key.
example_2.js โ Expiration Handling
$
Input:
const cache = new TimeLimitedCache();
cache.set(1, 42, 100); // expires in 100ms
setTimeout(() => {
cache.get(1); // after expiration
cache.count();
}, 200);
โบ
Output:
-1 (key expired)
0 (no unexpired keys)
๐ก Note:
After 200ms, the key has expired (duration was 100ms), so get() returns -1 and count() returns 0.
example_3.js โ Overwriting Keys
$
Input:
const cache = new TimeLimitedCache();
cache.set(1, 42, 1000);
cache.set(1, 100, 1000); // overwrite same key
cache.get(1);
cache.count();
โบ
Output:
true (key 1 existed and was unexpired)
100 (new value)
1 (still one key)
๐ก Note:
Second set() returns true because key 1 existed and hadn't expired. The value is updated to 100, and count remains 1.
Constraints
- 1 โค key โค 105
- 1 โค value โค 109
- 1 โค duration โค 106 milliseconds
- At most 2000 calls will be made to set, get, and count
- All test cases are generated such that count will return the expected value
Visualization
Tap to expand
Understanding the Visualization
1
Set Operation
Store key-value pair with expiration timestamp in hash map
2
Get Operation
Check if key exists and hasn't expired, return value or -1
3
Lazy Cleanup
Remove expired keys during access to free up memory
4
Count Operation
Count active keys and cleanup expired ones in the process
Key Takeaway
๐ฏ Key Insight: Lazy expiration checking combined with hash map efficiency provides O(1) operations while automatically managing memory through cleanup-on-access strategy.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code