Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the TimeMap class:
TimeMap() Initializes the object of the data structure.void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".Example 1:
Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]
Explanation
TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1); // return "bar"
timeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4); // return "bar2"
timeMap.get("foo", 5); // return "bar2"
Constraints:
1 <= key.length, value.length <= 100key and value consist of lowercase English letters and digits.1 <= timestamp <= 107timestamp of set are strictly increasing.2 * 105 calls will be made to set and get.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a giant notebook where people write down words with specific moments in time attached to them. The brute force approach involves looking through every single entry ever written down for a specific word, starting from the most recent, until you find the one that matches the time you care about.
Here's how the algorithm would work step-by-step:
class TimeMap:
def __init__(self):
self.storage_notebook = {}
def set(self, target_key: str, target_val: str, timestamp: int) -> None:
if target_key not in self.storage_notebook:
self.storage_notebook[target_key] = []
self.storage_notebook[target_key].append((timestamp, target_val))
def get(self, target_key: str, target_time: int) -> str:
if target_key not in self.storage_notebook:
return ""
# We store entries chronologically, so we check backwards to find the closest valid past time
all_entries = self.storage_notebook[target_key]
closest_value = ""
for entry_index in range(len(all_entries) - 1, -1, -1):
record_time, record_value = all_entries[entry_index]
# Future entries are ignored because time travel is impossible in this data store
if record_time <= target_time:
closest_value = record_value
break
# Returning the closest historical value ensures we satisfy the latest valid time constraint
return closest_valueTo handle values that change over time efficiently, we organize the information by name and keep a chronological diary of every value ever saved. When asked to find a value from the past, we use a clever searching shortcut to quickly flip to the closest timestamp without having to read through the entire history page by page.
Here's how the algorithm would work step-by-step:
class TimeMap:
def __init__(self):
self.storage_map = {}
def set(self, key_name: str, value_data: str, timestamp_val: int) -> None:
if key_name not in self.storage_map:
self.storage_map[key_name] = []
self.storage_map[key_name].append((timestamp_val, value_data))
def get(self, key_name: str, timestamp_val: int) -> str:
if key_name not in self.storage_map:
return ""
version_list = self.storage_map[key_name]
# Binary search is used to efficiently find the most recent valid timestamp without scanning linearly.
low_index = 0
high_index = len(version_list) - 1
target_value = ""
while low_index <= high_index:
mid_index = (low_index + high_index) // 2
record_time, record_val = version_list[mid_index]
if record_time <= timestamp_val:
target_value = record_val
low_index = mid_index + 1
else:
high_index = mid_index - 1
# Returning the closest valid historical value ensures we respect the timeline constraints.
return target_value| Case | How to Handle |
|---|---|
| Retrieving a key that does not exist in the data structure | Return an empty string immediately since no values are associated with the requested key. |
| Query timestamp is strictly less than the smallest timestamp stored for that key | Return an empty string because no valid historical value exists at or before the query time. |
| Query timestamp is greater than or equal to the largest timestamp stored for that key | Binary search will successfully locate and return the most recent value associated with that key. |
| Timestamps for a single key are inserted out of chronological order | Maintain a sorted list of timestamp-value pairs per key using binary search insertion or sort during retrieval to ensure correct ordering. |
| Multiple values are stored for the exact same key and timestamp | Overwrite or append the new value depending on constraints, ensuring the latest insertion for that specific timestamp is prioritized. |
| Extremely large volume of sets and gets across maximum-sized inputs | Use a hash map combined with binary search to guarantee logarithmic time complexity per retrieval and efficient scaling. |
| Timestamps spanning extreme integer ranges | Store timestamps as standard 32-bit or 64-bit integers to prevent overflow issues during comparisons. |
| Query timestamp matches an existing stored timestamp exactly | Binary search finds the exact match and returns its corresponding value directly. |