Time Based Key-Value Store solution explained

A time-based key-value store keeps, for each key, a list of (timestamp, value) pairs in the order they were set; because timestamps for a key only increase, that list is sorted, so get(key, t) is a binary search for the last timestamp at or before t. Set is O(1) amortized and get is O(log k), where k is the number of versions stored for that key.

By Published 7 min read

What you are building

Implement a class with two operations. set(key, value, time) records that the key held this value starting at this time. get(key, time) returns the value the key held at that moment, meaning the value from the latest set whose time is at or before the query time. If the key was never set at or before that time, return an empty string. In the usual version, each key's set calls arrive with strictly increasing times; ask about that, because the design depends on it.

An operation sequence invented for this page; outputs produced by the tested code
CallReturnsReason
set("theme", "light", 3)Stores the first version
get("theme", 2)""Nothing was set by time 2
get("theme", 3)"light"Exact timestamp match
get("theme", 8)"light"Latest version at or before 8
set("theme", "dark", 10)Stores a second version
get("theme", 9)"light"The dark version did not exist yet
get("theme", 50)"dark"Latest version overall
get("font", 5)""Key never set
An operation sequence invented for this page; outputs produced by the tested code. Scroll sideways on a small screen.

Why this design question shows up

It is a small design problem that hides a search problem. Interviewers like it because it checks whether you choose the data layout before writing methods, whether you notice the sorted-for-free property, and whether you can write a boundary binary search under a little pressure. It also has a natural link to real systems, versioned configuration and multi-version storage engines keep history in a similar way, which gives you something to discuss if the interviewer wants to go wider.

First version: scan the history

Store a list of (time, value) pairs per key. On get, walk the whole list and keep the pair with the greatest time that is not after the query. Set is O(1) and get is O(k) for k versions of that key. It does not even need the timestamps to arrive in order, which makes it a useful reference for testing.

class ScanStore:
    def __init__(self):
        self.entries = {}  # key -> list of (time, value)

    def set(self, key, value, time):
        self.entries.setdefault(key, []).append((time, value))

    def get(self, key, time):
        best_time, best_value = None, ""
        for t, v in self.entries.get(key, []):
            if t <= time and (best_time is None or t > best_time):
                best_time, best_value = t, v
        return best_value
Linear scan per get, O(k).

Binary search on a sorted history

Because each key's timestamps arrive in increasing order, appending keeps every history sorted by time with no extra work. A get then asks for the last entry whose time is at most t. The cleanest way to find it is to find the first entry whose time is greater than t, and step back one. If that first greater entry is at position 0, nothing qualifies and the answer is the empty string.

from bisect import bisect_right


class TimeStore:
    def __init__(self):
        self.times = {}   # key -> timestamps in increasing order
        self.values = {}  # key -> values in the same order

    def set(self, key, value, time):
        # assumes each key's timestamps arrive in increasing order
        self.times.setdefault(key, []).append(time)
        self.values.setdefault(key, []).append(value)

    def get(self, key, time):
        stamps = self.times.get(key)
        if not stamps:
            return ""
        i = bisect_right(stamps, time)  # count of stamps <= time
        return self.values[key][i - 1] if i else ""
Python: parallel lists per key and bisect_right, O(log k) per get.

Keeping timestamps and values in two parallel lists lets bisect_right work on plain numbers. If you store tuples instead, you have to search with a key function or a sentinel tuple, which is easy to get subtly wrong when two values compare differently. Either layout is fine as long as you can explain it.

class TimeStore {
  constructor() {
    this.history = new Map(); // key -> [{ time, value }] in time order
  }

  set(key, value, time) {
    if (!this.history.has(key)) this.history.set(key, []);
    this.history.get(key).push({ time, value });
  }

  get(key, time) {
    const list = this.history.get(key);
    if (!list) return "";
    let low = 0;
    let high = list.length; // find the first entry with time > query
    while (low < high) {
      const mid = (low + high) >> 1;
      if (list[mid].time <= time) low = mid + 1;
      else high = mid;
    }
    return low === 0 ? "" : list[low - 1].value;
  }
}
JavaScript: a Map of arrays and a hand-written upper-bound search.

Complexity

k is the number of versions stored for the key being read; N is all versions stored
DesignsetgetMemory
Scan each historyO(1)O(k)O(N)
Sorted history plus binary searchO(1) amortizedO(log k)O(N)
Sorted history, out-of-order sets via insertionO(k) per insertO(log k)O(N)
Balanced tree or skip list per keyO(log k)O(log k)O(N)
k is the number of versions stored for the key being read; N is all versions stored. Scroll sideways on a small screen.

Follow-ups interviewers ask

  • Timestamps can arrive out of order. Appending no longer keeps the list sorted. Insert in place with a binary search for the position, which is O(k) per insert because of shifting, or switch to an ordered structure such as a balanced tree, a skip list or a sorted container library, for O(log k) inserts.
  • Two sets for the same key at the same time. Decide whether the later call overwrites the earlier one, and check the last stored time before appending.
  • Memory grows forever. Discuss dropping versions older than a retention window, or compacting runs of identical values.
  • Many threads read and write. Per-key locks, or a copy-on-write list per key, keep readers from seeing a half-appended entry.
  • Range reads: every version between t1 and t2. Two boundary searches give the slice.

Edge cases

  • Get on a key that was never set: empty string, not an error.
  • Get at a time before the first set for that key: empty string.
  • Get at exactly a stored timestamp: that version, which is why the search uses 'greater than', not 'at least'.
  • Get far in the future: the latest version.
  • A value that is itself an empty string: the code returns it correctly, but say that callers cannot tell it apart from 'no value'. Returning None or a sentinel is an option if the interface allows.

Mistakes that come up

  • Using bisect_left instead of bisect_right, which misses an exact timestamp match.
  • Returning values[i] instead of values[i - 1], an off-by-one that returns the next version.
  • Indexing values[-1] in Python when i is 0, which silently returns the newest value instead of an empty string.
  • Sorting the whole history on every get, which turns O(log k) into O(k log k).
  • Storing all versions of all keys in one big list and filtering by key on each get.

How to explain it out loud

Fictional example

Choosing the layout before writing methods
Candidate
I'll keep a dictionary from key to its history. Since times for a key only increase, appending keeps each history sorted without any work.
Candidate
For get, I need the last time that is at or before the query. I'll find the first time that is strictly greater and step back one; if that's position zero, there's no value yet.
Interviewer
What if sets can come out of order?
Candidate
Then appending breaks the order. I could insert in the right place, which costs linear time for the shift, or use an ordered tree per key so both operations are log k.

The upper-bound search used in get is a close relative of the first-position loop in Binary Search. For more practice reading a boundary out of a sorted structure, Median of Two Sorted Arrays searches for a split point across two lists at once. Another 'design a class' question is LRU Cache, which pairs a dictionary with a linked list. Every walkthrough is on the coding problems hub.

Rehearsing design questions with Natively

Small design questions are graded heavily on how you set up the layout before coding, so practice saying your data structure choice first. Natively transcribes those practice rounds on Mac or Windows, and the saved transcript shows whether you stated the sorted-for-free assumption or skipped it. While practicing, it can read the class interface from a screenshot and suggest a layout to compare with yours. See the AI assistant for coding interviews for more.

Questions people ask

How do you implement a time-based key-value store?

Keep a dictionary from each key to its list of timestamps and values. Set appends to the list. Get binary searches that key's timestamps for the last one at or before the query time and returns its value, or an empty string.

Why is the history already sorted?

In the standard version, timestamps for each key arrive in increasing order, so appending keeps each list sorted without any extra work.

What is the time complexity?

Set is O(1) amortized and get is O(log k), where k is the number of versions stored for that key. Memory is proportional to all versions stored.

What if timestamps arrive out of order?

Insert each version at its sorted position, which is O(k) because of shifting, or use an ordered structure such as a balanced tree per key for O(log k) inserts and lookups.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP