Taro Logo

Time Based Key-Value Store

#3 Most AskedMedium
396 views
Topics:
ArraysBinary Search

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 <= 100
  • key and value consist of lowercase English letters and digits.
  • 1 <= timestamp <= 107
  • All the timestamps timestamp of set are strictly increasing.
  • At most 2 * 105 calls will be made to set and get.

Solution


Clarifying Questions

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:

  1. Are timestamps for the `set` operation always strictly increasing, or could they arrive out of order?
  2. What should `get` return if the exact timestamp requested does not exist, but there are earlier timestamps for that key?
  3. Can multiple values be set for the exact same key and the exact same timestamp, and if so, how should they be handled?
  4. What are the data types and expected maximum lengths for the keys and values?
  5. What should `get` return if the requested key does not exist at all in the data structure?

Brute Force Solution

Approach

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:

  1. Whenever someone gives you a word and a time, start by opening your notebook to all the pages associated with that specific word.
  2. Look at every single entry written for that word, examining them one by one.
  3. For each entry, check the time written next to it and compare it to the time you are searching for.
  4. Discard any entries that happened after the time you are looking for because those are too far in the future.
  5. Out of the remaining entries that happened at or before your target time, find the one that is closest to your target time.
  6. If you find a matching entry within that window, write down its value.
  7. If you check every single entry for that word and none of them fit the time requirement, conclude that nothing existed at that moment and return nothing.

Code Implementation

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_value

Big(O) Analysis

Time Complexity
O(n) – To answer a get request, we must retrieve all entries associated with the requested key and examine them one by one. If n represents the total number of timestamp-value entries stored for that specific key, we iterate through all n entries to check their time values. This linear scan across the entire list of historical entries for the key requires n operations in the worst-case scenario. Therefore, the total operations scale directly with the number of entries for that key, which simplifies to O(n).
Space Complexity
O(N) – To analyze the auxiliary space, let N represent the total number of key-value-timestamp entries inserted into the system. The data structure requires a hash map to store every unique key and its corresponding collection of time-value pairs. As new values are written down over time, they are added to these internal lists, meaning the extra memory consumed grows in direct proportion to the total number of entries N. Therefore, the overall auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To 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:

  1. When storing new information, group all the saved versions together under their specific name.
  2. Make sure every new version is automatically added to the end of its name group in the exact order it happened, ensuring time always moves forward.
  3. When someone asks for information from a specific point in time, first find the correct name group.
  4. If the exact requested time exists, immediately grab that version.
  5. If the exact time does not exist, look at all the recorded times in that group and find the most recent one that happened before your target time.
  6. Use a smart guessing strategy, like repeatedly splitting the timeline in half, to quickly zero in on the right moment instead of checking every single past entry one by one.
  7. If you look back and find that every recorded time happened after your target moment, return nothing because the information had not been created yet.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(log n) – When storing values, appending to the chronological list for a specific key takes constant O(1) time. When retrieving a value, we locate the key's history and perform a binary search over the list of timestamps to find the most recent valid version. If there are n timestamps recorded for a given key, repeatedly splitting the timeline in half requires at most log n steps. Therefore, the overall time complexity for the retrieval operation is driven by this binary search, resulting in O(log n).
Space Complexity
O(N) – To analyze the space complexity, let N represent the total number of set operations performed to store information over time. The primary data structure is a hash map that groups every saved version by its specific name, storing a chronological diary of values. Across all name groups, every unique timestamp-value pair is stored exactly once, resulting in a linear accumulation of entries. Therefore, the total extra memory required grows proportionally with the total number of stored records, leading to a space complexity of O(N).

Edge Cases

Retrieving a key that does not exist in the data structure
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Use a hash map combined with binary search to guarantee logarithmic time complexity per retrieval and efficient scaling.
Timestamps spanning extreme integer ranges
How to Handle:
Store timestamps as standard 32-bit or 64-bit integers to prevent overflow issues during comparisons.
Query timestamp matches an existing stored timestamp exactly
How to Handle:
Binary search finds the exact match and returns its corresponding value directly.
0/12 completed