Time Based Key-Value Store (LeetCode 981): Solution and Explanation

Medium
Hash Table
String
Binary Search
Design

Design a key-value store that remembers every value written for a key along with the timestamp of the write. A lookup with a key and a timestamp returns the value from the latest write at or before that timestamp, or an empty string if there is none.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The simplest design keeps, for every key, a list of every (value, timestamp) pair ever written. A lookup then scans that list and picks the entry with the largest timestamp that does not exceed the query. That is correct but linear per lookup, and with up to 200,000 operations all hitting one key it becomes quadratic.

The constraint that makes this easy is that timestamps for set arrive in strictly increasing order. So if you append each new pair to the end of the key's list, the list is automatically sorted by timestamp. There is no need for a balanced tree or for sorting after the fact.

On a sorted list, finding the last timestamp that is at most the query is a classic binary search for an upper boundary. Look at the middle entry. If its timestamp is at most the query, it is a valid candidate, so remember its value and search to the right for a later one. If its timestamp is too large, search to the left. When the search ends, the remembered value is the latest valid write, or the empty string if no entry qualified.

So the whole data structure is a hash map from key to an append-only sorted list. Writes are constant time, reads are logarithmic in the number of writes for that key, and the design mirrors how real multi-version stores keep history per key.

Approach: Hash map with binary search

  1. In the constructor, create self.store, a dictionary mapping each key to a list of [value, timestamp] pairs.
  2. In set, create an empty list for a new key, then append [value, timestamp]. Because timestamps increase, the list stays sorted.
  3. In get, set res = "" and fetch the key's list, or an empty list if the key was never set.
  4. Binary search with l = 0 and r = len(values) - 1. At midpoint m, if values[m][1] <= timestamp, record res = values[m][0] and move right with l = m + 1.
  5. Otherwise the midpoint is too recent, so move left with r = m - 1.
  6. Return res when the search range is empty.

Step-by-step example

set(foo, bar, 1), set(foo, bar2, 4), get(foo, 3), get(foo, 5), get(foo, 0)
  1. After both writes, store[foo] is [[bar, 1], [bar2, 4]].
  2. get(foo, 3): with l = 0 and r = 1, m = 0 has timestamp 1 ≤ 3, so res = bar and l = 1. Then m = 1 has timestamp 4 > 3, so r = 0. The search ends and returns bar.
  3. get(foo, 5): m = 0 gives res = bar and l = 1. Then m = 1 has timestamp 4 ≤ 5, so res = bar2 and l = 2. It returns bar2.
  4. get(foo, 0): m = 0 has timestamp 1 > 0, so r = -1 right away. No candidate was recorded, so it returns the empty string.

Code: Python, Java, C++

1class TimeMap:
2    def __init__(self):
3        self.store = {} # key : list of [val, time]
4
5    def set(self, key: str, value: str, timestamp: int) -> None:
6        if key not in self.store:
7            self.store[key] = []
8        self.store[key].append([value, timestamp])
9
10    def get(self, key: str, timestamp: int) -> str:
11        res = ""
12        values = self.store.get(key, [])
13        
14        # binary search
15        l, r = 0, len(values) - 1
16        while l <= r:
17            m = (l + r) // 2
18            if values[m][1] <= timestamp:
19                res = values[m][0]
20                l = m + 1
21            else:
22                r = m - 1
23        return res

Time and space complexity

Time

O(1) set, O(log n) get

A write is a dictionary lookup and a list append. A read is a binary search over the n entries stored for that key.

Space

O(N)

Every call to set stores one pair, so the structure grows linearly with the total number of writes N.

Other approaches

Linear scan from the end (time O(1) set, O(n) get, space O(N))

Walk the key's list backward and return the first entry whose timestamp is at most the query. It is simple and fast when queries usually ask for recent data, but the worst case is linear per lookup.

Sorted map per key (time O(log n) set and get, space O(N))

Store each key's history in a tree map and use a floor lookup, such as floorEntry in Java. It handles timestamps arriving out of order, at the cost of O(log n) writes.

Common mistakes

  • Returning on an exact timestamp match only. Most queries fall between writes, so you need the largest timestamp at or below the query, not equality.
  • Moving left when values[m][1] <= timestamp. A valid candidate means a later valid one might exist, so search to the right.
  • Forgetting the missing key case, which raises a KeyError if you index the dictionary directly instead of using get with a default.
  • Sorting the list on every set. The increasing timestamp guarantee makes the appended list sorted already.

Frequently asked questions

Why does binary search work for Time Based Key-Value Store?

Timestamps for each key arrive in strictly increasing order, so appending keeps each list sorted. Binary search on a sorted list finds the last timestamp at or below the query in logarithmic time.

What should get return if no timestamp is small enough?

It returns an empty string. The search never records a candidate in that case, so res keeps its initial value.

Can I use bisect in Python?

Yes. Keep a separate list of timestamps per key and call bisect_right(times, timestamp) - 1 to find the index of the latest valid write. It is equivalent to the hand-written search.

What if timestamps were not increasing?

Then appending would no longer keep the list sorted. A tree map per key, or inserting with bisect.insort, would restore the sorted order needed for the lookup.