← Whiteboard questions

Time Based Key Value Store

Design a store that returns the value a key had at a given time

DSA, Medium, Binary Search

Which structure or algorithm, and what does it cost.

Build a class TimeStore that keeps the history of values for each key. set(key, value, time) records that key holds value from time on. get(key, time) answers with the value from the most recent record of key made at or before time. With no such record, it answers with an empty string. The input is a list of calls. The output lists the answers of the get calls, in order.

Examples

Input ops = [["set", "door", "open", 4], ["get", "door", 4], ["get", "door", 2], ["set", "door", "shut", 9], ["get", "door", 6], ["get", "door", 12]]
Output ["open", "", "open", "shut"]
Why A get at time 4 matches the set. At time 2 nothing was saved yet, so the answer is empty. At time 6 the latest set not after 6 is at time 4. At time 12 it is at time 9.
Input ops = [["set", "a", "x", 1], ["set", "b", "y", 2], ["get", "a", 5], ["get", "b", 1], ["get", "c", 3]]
Output ["x", "", ""]
Why Keys are separate. Key a at time 5 gives x. Key b has nothing at time 1. Key c was never set.
Input ops = [["get", "k", 1], ["set", "k", "v", 5], ["get", "k", 5], ["get", "k", 4]]
Output ["", "v", ""]
Why Edge case: a get before any set. A get at exactly the set time returns that value, and one tick earlier does not.

Constraints

Your answer must contain

Target Aim for O(1) time for set, O(log k) time for get, and O(total sets) memory, where k is the number of sets for that key.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

A get asks for the latest time at or before a given time. How could you keep the saved times so that this is quick to find?

Hint 2 the approach

Keep a separate list of saved values for each key. Times only rise for a key, so each list stays sorted without extra work.

Hint 3 the key step

For a get, search that key's list for the last entry whose time is at most the asked time. If there is none, the answer is an empty string.

Walkthrough

Full walkthrough brute force to best

Brute force

Keep every set in one list of key, value and time. For a get, scan the whole list and remember the matching entry with the largest time that is at most the asked time. A set is O(1), and a get is O(total sets). With 200,000 calls, repeated gets can reach 10^10 steps.

Best method

Group the saves by key: a dictionary from key to a list of pairs of time and value. A set appends to its key's list, which is O(1), and the list stays sorted by time because the times for one key only rise. A get finds the key's list and binary searches for the first entry whose time is greater than the asked time. The entry just before it is the answer. If that position is 0, no entry is old enough, so return an empty string. A key that was never set counts as an empty list.

Hand trace

Run on example 1. Set door at 4: the list is [(4, open)]. Get door at 4: no entry has a time above 4, so the first such position is 1, and the answer is the entry at position 0, open. Get door at 2: the entry at position 0 is already above 2, so no entry is old enough and the answer is empty. Set door at 9: the list is [(4, open), (9, shut)]. Get door at 6: the first entry above 6 is position 1, so the answer is position 0, open. Get door at 12: no entry is above 12, so the answer is position 1, shut.

Code

class TimeStore:
    def __init__(self):
        self.data = {}              # key -> list of (time, value), times rising
    def set(self, key, value, time):
        self.data.setdefault(key, []).append((time, value))
    def get(self, key, time):
        items = self.data.get(key, [])
        lo, hi = 0, len(items)      # find the first entry with a time above `time`
        while lo < hi:
            mid = (lo + hi) // 2
            if items[mid][0] <= time:
                lo = mid + 1
            else:
                hi = mid
        return items[lo - 1][1] if lo else ""

Time and memory

set is O(1). get is O(log k) for k sets of that key, from the binary search. Memory is O(total sets), one pair per set.

Common mistakes

  • Returning the value at the first time above the asked time. The answer is the entry before it, the last time that is not after the asked time.
  • Using a strict comparison so that a get at exactly the set time misses. A set time counts as at or before itself.
  • Keeping one list for all keys, or searching a list that mixes keys. Each key needs its own sorted list.
  • Forgetting the empty answer when the key is missing or the asked time is before the first set.

Related problems

More Binary Search problems
Time Based Key Value Store: walkthrough and Python solution