← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
Design a cache where every entry has a time-to-live (TTL): it is readable for a fixed window after insertion, then disappears.
Implement the TTLCache class:
TTLCache() Initializes an empty cache.void put(int currentTime, String key, int value, int ttl) Stores key -> value with an expiry time of currentTime + ttl. If key already exists, the entry (and its TTL) is refreshed with the new value and new expiry.int get(int currentTime, String key) Returns the value for key if it is present and not yet expired at currentTime. Otherwise returns -1.int size(int currentTime) Returns the number of entries that are still alive at currentTime.
Expiry semantics (this is the part the interviewer will press on):t iff t < expiry.t == expiry the entry is already expired (it lived for exactly ttl units, from putTime up to but not including putTime + ttl).currentTime values passed in across calls are non-decreasing.
Design constraints:put and get should be O(1) average.get must not return expired values — if the key is present but expired, return -1 (and you may remove it then, or defer deletion to size).size must return an accurate count at currentTime, so expired entries must actually be removed before it answers.At t=3, a (expiry=4) and b (expiry=12) are both alive → size=2. put at t=5 refreshes "a" to value=30, new expiry=10. get at t=6 sees the new value. At t=7, a (10>7) and b (12>7) still alive → size=2.
"a" (expiry=3) is expired by t=4; size(4) sweeps it away and returns 1 (only "b" left). get(4,"a") confirms it is gone. By t=10, "b" (expiry=6) is also expired → size=0.