Implement a timestamped map
GustoSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to design a time-indexed key-value store that supports efficient lookups of historical values using binary search.
Problem Statement
Design a TimeMap class that supports storing multiple values for the same key at different timestamps and retrieving the value for a specific key at a specific timestamp.
Implement the TimeMap class:
__init__(): Initializes the object.set(key: str, value: str, timestamp: int) -> None: Stores thekeyandvaluewith the giventimestamp.get(key: str, timestamp: int) -> str: Returns the value associated with thekeysuch thattimestamp_prev <= timestamp. If there are multiple such values, return the value associated with the largesttimestamp_prev. If no such value exists, return an empty string"".
Constraints
1 <= key.length, value.length <= 1001 <= timestamp <= 10^7- All
timestampvalues insetare strictly increasing for a singlekey. - At most
2 * 10^5calls will be made tosetandget.
Examples
tm = TimeMap()
tm.set("foo", "bar", 1)
tm.get("foo", 1) # returns "bar"
tm.get("foo", 3) # returns "bar" (since 1 <= 3)
tm.set("foo", "bar2", 4)
tm.get("foo", 4) # returns "bar2"
tm.get("foo", 5) # returns "bar2"
Edge Cases
- Searching for a timestamp smaller than any recorded for that key.
- Searching for a key that does not exist.
- Multiple
setoperations at different timestamps for the same key.
Hints
Hint 1
Use a hash map to store keys, where each key maps to a list of (timestamp, value) pairs.
Hint 2
Since timestamps are inserted in strictly increasing order, the list for each key is naturally sorted by timestamp.
Hint 3
Perform a binary search on the list of (timestamp, value) pairs to find the largest timestamp that is less than or equal to the requested timestamp.
Follow-up questions
- How would your implementation change if timestamps were not provided in strictly increasing order?
- What is the time complexity of `get` and `set`? Can you optimize `get` further if the frequency of queries for a specific key is extremely high?
- How would you modify the system to delete a specific version of a key-value pair?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.