Time Based Key-Value Store

Medium

Topics
Hash TableBinary SearchDesign

Design TimeMap with set(key, value, timestamp) and get(key, timestamp). get returns the value set for key with the largest timestamp <= timestamp, or an empty string if none.

Example 1

returnsTimeMap()set(foo, bar, 1)get(foo, 1)barget(foo, 3)barset(foo, bar2, 4)get(foo, 4)bar2get(foo, 5)bar2
A get wants the newest value at or before a timestamp, not an exact match.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["TimeMap","set","get","get","set","get","get"], values = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,bar,bar,null,bar2,bar2]

Constraints

  • 1 <= key.length, value.length <= 100
  • set timestamps are strictly increasing per problem.
  • At most 2*10^5 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because set timestamps are increasing, each key stores an ascending list of (timestamp, value). A get is then a binary search for the rightmost timestamp not exceeding the query.

Approach

  1. Keep a map from key to a list of (timestamp, value) pairs appended in order.
  2. For get, binary search that list for the largest timestamp <= query.
  3. Return the paired value, or "" if none qualifies.

Dry Run

TimeMap()
  set foo bar  1   -> null    store[foo] = [(1, bar)]
  get foo 1        -> "bar"   exact match on the timestamp counts
  get foo 3        -> "bar"   nothing newer than 3, so the 1 still answers
  set foo bar2 4   -> null    store[foo] = [(1, bar), (4, bar2)]
  get foo 4        -> "bar2"
  get foo 5        -> "bar2"
  get foo 0        -> ""      nothing at or before 0
answer null|null|bar|bar|null|bar2|bar2
The binary search finds the first entry STRICTLY AFTER the timestamp, so the
answer sits one position back at arr[lo - 1], and `if lo else ""` covers the case
where even the oldest entry is too new. Return arr[lo] instead and every get
comes back empty or out of range -- the whole sequence degenerates to blanks.
The comparison is `<=`, not `<`. An exact timestamp match is a valid answer, and
`<` steps over it: `get foo 1` then returns "" and `get foo 4` returns "bar",
each reading the value from before the set it should have seen.
Appends arrive in increasing timestamp order, which is the only reason a binary
search is legal with no sorting anywhere. If timestamps could arrive out of order
this would need an insort, and the amortised O(1) set would become O(n).

Complexity

  • Time — O(log n) get: binary search per get; O(1) amortized set.
  • Space — O(n): all set entries.

Common Pitfalls

  • The binary search finds the first entry after the timestamp, so the answer is arr[lo - 1]. Returning arr[lo] reads one past the newest match and raises IndexError at the end of the list.
  • The comparison is <=, not <. An exact timestamp match is a valid answer, and < steps over it -- get at the moment of a set returns the previous value or nothing.
  • Appends are already in increasing timestamp order, which is the only reason a binary search is legal without sorting. If timestamps could arrive out of order this would need an insort.

Full Solution — all languages

class TimeMap:
    def __init__(self):
        self.store = {}
    def set(self, key, value, timestamp):
        self.store.setdefault(key, []).append((timestamp, value))
    def get(self, key, timestamp):
        arr = self.store.get(key, [])
        lo, hi = 0, len(arr)
        while lo < hi:                 # binary search: timestamps are increasing
            mid = (lo + hi) // 2
            if arr[mid][0] <= timestamp:
                lo = mid + 1
            else:
                hi = mid
        return arr[lo - 1][1] if lo else ""
SensAI
Beta
Tap the mic to stop voice mode