← 返回 netflix 的题目列表Timed KV Cache
类型:online_judge
Implement a timed key-value cache. Design a data structure that supports the following operations:
put(key: str, value: any, ttl: int): Store a key-value pair (key, value) where ttl is the time-to-live in seconds for the given key.
get(key: str) -> any: Return the value associated with the key. If the key does not exist or has expired, return null.
Constraints
Keys and values are strings.
ttl is a positive integer.
Achieve a time complexity as close to O(1) as possible for each operation.
Example
cache = TimedKVCache()
cache.put("apple", "fruit", 5) # Set key "apple" with value "fruit" to expire in 5 seconds
cache.get("apple") # Returns "fruit"
# Wait for 5 seconds
cache.get("apple") # Returns null as "apple" has expired
Example
Input
put apple fruit 5
get apple
wait 5
get apple
Output
fruit
null