Published

Time Based Key-Value Store (LeetCode 981)

A hash map of sorted lists and one binary search, the bisect_left bug that fails 5% of random reads, what changes when timestamps arrive out of order, and Python, Java and Go code tested against brute force.

On this page · 11 sections
  1. First version: scan back from the newest entry
  2. The fast version: binary search for the first timestamp that is too new
  3. The bug: bisect_left
  4. Tested code: Python, Java and Go
  5. When timestamps can arrive out of order
  6. Where this shows up outside LeetCode
  7. Complexity
  8. Common mistakes
  9. Related problems
  10. FAQ
  11. Learn the pattern

Design a class TimeMap that stores several values for the same key at different timestamps, and returns the value a key had at a given time.

  • set(key, value, timestamp) stores value for key at timestamp.
  • get(key, timestamp) returns the value from the latest set whose timestamp is less than or equal to timestamp. If there is none, it returns "".
CallReturnsWhy
set("foo", "bar", 1)
get("foo", 1)"bar"exact match at 1
get("foo", 3)"bar"nothing at 3; the latest before it is 1
set("foo", "bar2", 4)
get("foo", 4)"bar2"exact match at 4
get("foo", 5)"bar2"latest at or before 5 is 4
get("foo", 0)""nothing at or before 0

LeetCode’s constraints: timestamps are between 1 and 10⁷, keys and values are up to 100 characters, there are at most 2 × 10⁵ calls in total, and, the line that matters, all timestamps passed to set are strictly increasing. Read that line twice. It means that if you append each new value to a list per key, that list is already sorted by time, and you never have to sort anything.

So the problem is: one hash map from key to a sorted list of (timestamp, value), and get asks for the last entry whose timestamp is at most the query. That is a floor lookup, and on a sorted list a floor lookup is a binary search.

First version: scan back from the newest entry

class TimeMapLinear:
    def __init__(self):
        self.h = {}

    def set(self, key, value, timestamp):
        self.h.setdefault(key, []).append((timestamp, value))

    def get(self, key, timestamp):
        for t, v in reversed(self.h.get(key, [])):
            if t <= timestamp:
                return v
        return ""

This is correct, and for a lot of real workloads it is even fast: if most reads ask for “now”, the newest entry matches on the first step. The worst case is a read for an old timestamp on a key with a long history, which walks the whole list.

LeetCode’s tests include that case. I timed one key with n set calls followed by n get calls at random timestamps. At n = 10,000 the scan took 1.10 seconds in Python; at n = 100,000, which is inside the limits, it took 111.3 seconds (I ran it separately; the script skips it to keep its own run short). The binary search version below did the 100,000 case in 0.103 seconds.

The fast version: binary search for the first timestamp that is too new

The cleanest way to find “the last timestamp ≤ t” is to find the first timestamp > t and step one to the left. In Python that is bisect_right:

import bisect

class TimeMap:
    def __init__(self):
        self.times = {}
        self.values = {}

    def set(self, key, value, timestamp):
        self.times.setdefault(key, []).append(timestamp)
        self.values.setdefault(key, []).append(value)

    def get(self, key, timestamp):
        times = self.times.get(key)
        if not times:
            return ""
        i = bisect.bisect_right(times, timestamp)  # first index with time > timestamp
        return self.values[key][i - 1] if i else ""

Two parallel lists instead of one list of tuples is deliberate. bisect on a list of (timestamp, value) tuples works, but you have to search for (timestamp, chr(0x10FFFF)) or similar to make ties land on the right side, and that trick breaks the day values are not strings. Python 3.10+ also has bisect_right(entries, timestamp, key=lambda e: e[0]), which is fine if your judge runs 3.10 or later.

Trace it on a key with times [1, 4, 7, 10]:

Querybisect_righti - 1Returns
00none""
421value at 4
621value at 4
732value at 7
9943value at 10

i == 0 means every stored timestamp is newer than the query, so nothing existed yet. That is the only special case.

The bug: bisect_left

Swap bisect_right for bisect_left and the code still looks right. It is wrong exactly when the query equals a stored timestamp: bisect_left returns the index of that entry, so i - 1 is the entry before it. On LeetCode’s own example, get("foo", 1) returns "" instead of "bar", and get("foo", 4) returns "bar" instead of "bar2".

I ran both against a brute-force reference on 2,000 random sequences of 30 operations each. The bisect_left version was wrong on 1,544 of 29,777 reads, about 5%. Every one of them was an exact-timestamp read. That is the kind of bug that passes a quick test with “in-between” timestamps and fails the hidden ones.

If you write the loop by hand, the same mistake shows up as < where you needed <=:

int lo = 0, hi = ts.size();          // find the first index with time > timestamp
while (lo < hi) {
    int mid = (lo + hi) >>> 1;
    if (ts.get(mid) <= timestamp) lo = mid + 1; else hi = mid;
}
return lo == 0 ? "" : values.get(key).get(lo - 1);

<= pushes lo past entries equal to the query, so lo - 1 lands on the match itself. With <, lo stops on the match and you return the one before it.

Tested code: Python, Java and Go

The full files, with the stress test and timings, are in course-code/problems/time-based-key-value-store/ in the site’s GitHub repo. Python 3.13.5, OpenJDK 21.0.13 and Go 1.27.3 on the same machine.

Python

The TimeMap class above, plus a linear version, the bisect_left version and an any-order version, all checked against brute force:

LeetCode example: set(foo,bar,1) get 1, get 3, set(foo,bar2,4) get 4, get 5, get 0, get(nope)
  TimeMapLinear    ['bar', 'bar', 'bar2', 'bar2', '', '']
  TimeMap          ['bar', 'bar', 'bar2', 'bar2', '', '']
  TimeMapBuggy     ['', 'bar', 'bar', 'bar2', '', '']
  TimeMapAnyOrder  ['bar', 'bar', 'bar2', 'bar2', '', '']

Stress test, 2,000 random runs of 30 operations each, against brute force
  increasing timestamps, TimeMapLinear    wrong 0 of 29777 gets
  increasing timestamps, TimeMap          wrong 0 of 29777 gets
  increasing timestamps, TimeMapBuggy     wrong 1544 of 29777 gets
  increasing timestamps, TimeMapAnyOrder  wrong 0 of 29777 gets
  any-order timestamps,  TimeMap          wrong 7215 of 29784 gets
  any-order timestamps,  TimeMapAnyOrder  wrong 0 of 29784 gets

One key, n sets then n gets at random timestamps
  n= 10,000  linear scan    1.10 s   binary search 0.007 s
  n=100,000  linear scan   skipped   binary search 0.103 s

Java

import java.util.*;

class TimeMap {
    private final Map<String, List<Integer>> times = new HashMap<>();
    private final Map<String, List<String>> values = new HashMap<>();

    public void set(String key, String value, int timestamp) {
        times.computeIfAbsent(key, k -> new ArrayList<>()).add(timestamp);
        values.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
    }

    public String get(String key, int timestamp) {
        List<Integer> ts = times.get(key);
        if (ts == null) return "";
        int lo = 0, hi = ts.size();          // first index with time > timestamp
        while (lo < hi) {
            int mid = (lo + hi) >>> 1;
            if (ts.get(mid) <= timestamp) lo = mid + 1; else hi = mid;
        }
        return lo == 0 ? "" : values.get(key).get(lo - 1);
    }
}

The test file also has a TreeMap version (below) and cross-checks the two on 200,000 random operations over 50 keys:

TimeMap     [bar, bar, bar2, bar2, , ]
TimeMapTree [bar, bar, bar2, bar2, , ]
cross-check: 0 differences in 100159 gets
round 1, n=100,000 sets + 100,000 gets: lists 37 ms, TreeMap 55 ms
round 1, n=1,000,000 sets + 1,000,000 gets: lists 655 ms, TreeMap 1225 ms
round 2, n=100,000 sets + 100,000 gets: lists 37 ms, TreeMap 47 ms
round 2, n=1,000,000 sets + 1,000,000 gets: lists 592 ms, TreeMap 1089 ms
round 3, n=100,000 sets + 100,000 gets: lists 31 ms, TreeMap 56 ms
round 3, n=1,000,000 sets + 1,000,000 gets: lists 630 ms, TreeMap 1565 ms

Go

type entry struct {
	ts  int
	val string
}

type TimeMap struct {
	h map[string][]entry
}

func Constructor() TimeMap { return TimeMap{h: map[string][]entry{}} }

func (m *TimeMap) Set(key, value string, timestamp int) {
	m.h[key] = append(m.h[key], entry{timestamp, value})
}

func (m *TimeMap) Get(key string, timestamp int) string {
	es := m.h[key]
	// first index whose timestamp is greater than the query
	i := sort.Search(len(es), func(i int) bool { return es[i].ts > timestamp })
	if i == 0 {
		return ""
	}
	return es[i-1].val
}

sort.Search returns the first index where the predicate is true, so the predicate has to be “too new” (>), not “good enough” (<=). A nil slice for a missing key has length 0, so the unknown-key case needs no extra check.

["bar" "bar" "bar2" "bar2" "" ""]
n=100000 sets + 100000 gets: 35 ms (sink 588913)
n=1000000 sets + 1000000 gets: 531 ms (sink 6889128)

When timestamps can arrive out of order

The usual follow-up: “drop the increasing-timestamp guarantee”. It is a real situation. Events from phones arrive late, and replicas replay writes in a different order from the one they happened in.

The appended list is no longer sorted, and the stress test shows what that costs: the plain TimeMap returned the wrong value on 7,215 of 29,784 reads, about a quarter. Three fixes:

  • Insert in place. Find the position with bisect_left and list.insert there; if the timestamp already exists, overwrite the value. Reads stay O(log n), writes become O(n) because the list shifts. In Python and Java that shift is a memory move and is fast in practice until a single key has hundreds of thousands of versions. This is TimeMapAnyOrder in the Python file, and it was right on every read.
  • A sorted map per key. Java’s TreeMap.floorEntry(t) is exactly this query. O(log n) for both reads and writes, and no ordering assumption at all. The cost is a tree node per entry: in my run it was about twice as slow as the lists, 1.1 to 1.6 seconds against about 0.6 for a million writes and reads on one key. C++ has std::map::upper_bound; Python needs a third-party package such as sortedcontainers.
  • Buffer and sort. If late writes are rare and you can tolerate a short delay, collect out-of-order writes and merge them in batches. That is how log-structured stores handle it, but it is out of scope for an interview answer.

In an interview I would write the list version first, because it is what the constraints ask for, then say that the guarantee is what makes the append safe and name TreeMap for the general case. Using TreeMap from the start is accepted on LeetCode and is fine in Java; just know why the lists are faster.

What should happen when the same key is set twice at the same timestamp? LeetCode never does it. In the any-order version I made the later write win, which matches what a database does with two writes at the same version. Say which rule you chose.

Where this shows up outside LeetCode

This structure is a version history with “as of” reads, and it is everywhere once you look:

  • MVCC in databases. Each row keeps several versions tagged with a commit timestamp, and a transaction reading at snapshot t sees the newest version at or before t. That is get(key, t) with a version chain. The MVCC transactions lesson in the Go database course builds one.
  • Config and feature-flag history. “What was this flag set to when the incident started at 14:02?” is a floor lookup on the flag’s change log.
  • Kafka’s offsetsForTimes. A consumer asks for the first offset at or after a timestamp, and the broker answers by binary-searching a per-segment time index. Same idea, the other direction.
  • Price history. “What was the price of this item when the order was placed?” Store each price change with its start time and look up the floor. Copying the price into the order row is usually better, but the history still needs this query for reports.

Complexity

VersionsetgetWhen to use
Scan back from the newestO(1)O(n) per keyReads mostly ask for “now”
Lists + binary searchO(1) amortisedO(log n)Timestamps increase (the LeetCode case)
Insert in placeO(n)O(log n)Out-of-order writes are rare
Sorted map per key (TreeMap)O(log n)O(log n)Timestamps in any order

Space is O(total number of set calls) for all of them.

Common mistakes

  • bisect_left or < in the hand-written loop. Exact-timestamp reads return the previous value. 5% of random reads in the stress test, including LeetCode’s first example.
  • Sorting inside get. The list is already sorted because timestamps increase. Sorting on every read turns O(log n) into O(n log n) and times out.
  • Storing only the latest value per key. Then get("foo", 3) after set("foo", "bar2", 4) returns "bar2", a value from the future.
  • A global list of all keys’ entries. One list per key keeps each binary search over that key’s history only.
  • Returning null or None instead of "". The problem asks for an empty string.
  • Forgetting the unknown key. self.times[key] raises KeyError; use .get or check first.
ProblemWhat changesDifficulty
704. Binary SearchThe plain exact-match search, to get the loop rightEasy
35. Search Insert PositionLower bound: the first index ≥ targetEasy
34. Find First and Last Position of Element in Sorted ArrayLower bound and upper bound in one problem; good practice for the < vs <= choiceMedium
1146. Snapshot ArrayThe same version-history structure, with snapshot ids instead of timestampsMedium
2034. Stock Price FluctuationTimestamps arrive out of order and can be corrected; needs a map plus heapsMedium

LeetCode 981 is in week 5 of Grind 75, under binary search, and in the DSA master sheet.

FAQ

Why is Time Based Key-Value Store a binary search problem?

Timestamps passed to set are strictly increasing, so each key’s list of timestamps is sorted as it is built. get asks for the last timestamp less than or equal to the query, which is a floor lookup on a sorted list. Binary search finds it in O(log n).

Should I use bisect_left or bisect_right?

bisect_right, then take index i - 1. bisect_right returns the first position with a timestamp greater than the query, so the entry before it is the latest one at or before the query. bisect_left gets exact matches wrong: on LeetCode’s example it returns "" for get("foo", 1).

Can I use a TreeMap in Java?

Yes. TreeMap.floorEntry(timestamp) answers the query directly and also works if timestamps arrive out of order. It is O(log n) per call like the list version, but in my runs it was about twice as slow on a million operations, because every entry is a tree node.

What is the time and space complexity?

With per-key lists and binary search, set is O(1) amortised and get is O(log n), where n is the number of values stored for that key. Space is O(total number of set calls).

What if timestamps are not in increasing order?

Then appending no longer keeps the list sorted. Either insert each timestamp at its sorted position (O(n) per set, O(log n) per get) or use a sorted map per key such as Java’s TreeMap (O(log n) for both).

Learn the pattern

  • Binary search lesson in the free DSA Patterns course: the lower-bound template, binary search on the answer, exercises and a quiz.
  • DSA patterns cheat sheet, to see where binary search sits among the other patterns.
  • Grind 75, where this problem sits in week 5.