Cache with Expiry - Problem
Design and implement a Cache with Expiry that stores key-value pairs with a time-to-live (TTL) mechanism.
Your cache should support the following operations:
put(key, value, ttl)- Store a key-value pair that expires after ttl secondsget(key)- Retrieve the value for a key if it hasn't expired, otherwise returnnulldelete(key)- Remove a key from the cachesize()- Return the number of non-expired keys currently in the cache
Keys expire based on the TTL (time-to-live) value provided when they were stored. Once a key expires, it should be treated as if it doesn't exist in the cache.
Input & Output
Example 1 — Basic Cache Operations
$
Input:
operations = [["put","key1","value1",5], ["get","key1"], ["size"], ["get","key1"], ["size"]]
›
Output:
[null, "value1", 1, null, 0]
💡 Note:
Put key1 with 5-second TTL, get immediately returns value1, size is 1. After 5+ seconds, key1 expires so get returns null and size becomes 0.
Example 2 — Multiple Keys with Different TTLs
$
Input:
operations = [["put","a","apple",3], ["put","b","banana",10], ["get","a"], ["get","b"], ["size"]]
›
Output:
[null, null, "apple", "banana", 2]
💡 Note:
Store 'a' for 3 seconds and 'b' for 10 seconds. Both are accessible initially, and cache size is 2.
Example 3 — Delete Operation
$
Input:
operations = [["put","x","test",60], ["delete","x"], ["get","x"], ["delete","x"]]
›
Output:
[null, true, null, false]
💡 Note:
Put 'x' with 60-second TTL. Delete returns true (key existed). Get returns null (key was deleted). Second delete returns false (key doesn't exist).
Constraints
- 1 ≤ operations.length ≤ 1000
- operations[i] is one of ["put", "get", "delete", "size"]
- 1 ≤ key.length, value.length ≤ 100
- 1 ≤ ttl ≤ 109 seconds
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code