Problem Description
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)
, get(key)
, and count()
.
Key Insights
- Each key in the cache has an associated expiration time, calculated as the current time plus the duration.
- The
set
method should update the value of an existing key if it already exists and return whether the key was previously un-expired. - The
get
method should return the value of a key if it is still valid, or -1 if it has expired. - The
count
method should return the number of keys that have not expired.
Space and Time Complexity
Time Complexity: O(1) for set
, get
, and count
operations.
Space Complexity: O(n) where n is the number of keys stored in the cache.
Solution
To solve the problem, we can utilize a hash map (dictionary) to store the keys along with their values and expiration times. The hash map will allow us to efficiently check if a key exists and to retrieve or update its associated value and expiration time. Specifically, we will store each key as the dictionary key and a tuple containing its value and expiration time as the dictionary value. The approach allows us to quickly determine if a key is expired during retrieval operations.