Time Based Key-Value Store

Store every value a key was given, with the time it was set, and look up what the key held at any moment.

Write a class TimeMap that stores values for keys, where a key keeps every value it was ever given. set(key, value, timestamp) stores value for key at the time timestamp. get(key, timestamp) returns the value set for key most recently at or before timestamp, or "" if there is none. Timestamps passed to set are strictly increasing.

Example
set("foo", "bar", 1)
get("foo", 1) returns "bar"
get("foo", 3) returns "bar"
set("foo", "bar2", 4)
get("foo", 4) returns "bar2"
get("foo", 5) returns "bar2"
Solution

The Idea

Picture a notice board where each new note carries the time it was pinned, and old notes are never taken down. To know what the board said at 3 o'clock, you look for the last note pinned at or before 3. This problem asks for the same thing in code: each key keeps all its values, each with the time it was set, and get asks what the key held at a given time.

Look at the example. "foo" gets "bar" at time 1 and "bar2" at time 4. get("foo", 4) is easy, because a value was set at exactly 4. But get("foo", 3) asks about a time when nothing was set. What should it return?

It returns "bar", because at time 3 "bar" was still the newest value, and "bar2" only came at 4. So get does not look for an exact time. It looks for the latest set at or before that time. Look at the picture below.

The history of foo on a time line: bar set at 1, bar2 set at 4. get(foo, 3) goes back to the latest set at or before 3 and returns bar, and get(foo, 0) returns an empty string. In the list, the test timestamp <= 3 gives yes for (1, bar) and no for (4, bar2), and the last yes is the answer.

On the time line at the top, "bar" was set at 1 and "bar2" at 4. The orange arrow starts at 3 and goes back to the latest set before it, at 1, so get("foo", 3) returns "bar". At 0 nothing had been set yet, so get("foo", 0) returns the empty string "".

The bottom row, the list for "foo", shows the same history as a list, oldest first. Each entry is asked one question: is its timestamp <= 3? (1, "bar") says yes and (4, "bar2") says no. Because the list is in time order, all the yes answers come before all the no answers, and the answer to get is the last yes.

Finding the last yes in such a list does not need a look at every entry. Check the middle entry: a yes means the answer is there or to its right, and a no means it is to the left. Every check throws away half of the entries still in play. Searching a sorted list by halving it like this is binary search, and it finds the last yes among a thousand entries in about ten checks.

Solution Approach

Turning that idea into code means settling three things: where each key's history is kept, how it stays in time order, and how get finds the last yes. A ready-made Java class that does the search for you comes last, as an optional alternative.

Where each key's history is kept

Where does the class keep the values? In a HashMap from each key to a list of entries. An entry holds one timestamp with its value. A Java record, a class declared in one line that only holds a few fields, fits that well. Finding a key's list is a single lookup, however many keys are stored.

Keeping each history in time order

Does a list ever need sorting? No. Timestamps passed to set are strictly increasing, so a new entry always belongs at the end of its key's list. set only appends, and every list stays oldest first on its own.

Finding the last entry at or before a time

How does get find the last yes? The simple way walks the list from the start and remembers the last entry whose timestamp is <= the given time. That reads every entry, which gets slow for a key that was set thousands of times.

Binary search keeps two positions, lo and hi, around the part of the list still in play, and found, the last yes seen so far. Take a key "lamp" with the history (2, "off"), (5, "on"), (9, "dim"), (14, "off"), and the call get("lamp", 8). At first lo is 0 and hi is 3.

The middle position is 1, with timestamp 5. That is <= 8, a yes, so found becomes 1 and lo moves to 2 to look for a later yes. The next middle is 2, with timestamp 9, a no, so hi moves to 1. Now lo is past hi, the search stops, and position 1 gives "on".

found starts at -1, which means no yes yet. If it is still -1 at the end, no entry was early enough, and get returns "".

Optional: a TreeMap per key

Is there a ready-made way? A TreeMap is a Java map that keeps its keys sorted. With one TreeMap<Integer, String> per key, from timestamp to value, floorEntry(timestamp) returns the entry with the largest timestamp at or before the given one, or null if there is none. It also works when timestamps arrive out of order, but each entry takes more memory than a slot in an ArrayList.

Java Solution

The class has four parts, one for each piece of the approach:

  • Entry: a record holding one timestamp with its value.
  • store: the HashMap from each key to its list of entries, oldest first.
  • set: appends a new Entry to the key's list. computeIfAbsent creates the list the first time a key is set.
  • get: binary searches the key's list for the last entry with a timestamp <= the given time, and returns "" for a key that was never set or when found stays -1.

The main method runs the example, then asks for "foo" at time 0 and for a key that was never set. Last, it gives "lamp" four entries and asks for a time between two sets, an exact set time and a time after the last set.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TimeMap {

    private record Entry(int timestamp, String value) {}

    // for each key, its entries in the order they were set; timestamps only increase
    private final Map<String, List<Entry>> store = new HashMap<>();

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

    public String get(String key, int timestamp) {
        List<Entry> entries = store.get(key);
        if (entries == null) {
            return "";                          // key never set
        }
        int lo = 0;
        int hi = entries.size() - 1;
        int found = -1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (entries.get(mid).timestamp() <= timestamp) {
                found = mid;                    // fits; a later entry may fit too
                lo = mid + 1;
            } else {
                hi = mid - 1;                   // too late: look left
            }
        }
        return (found == -1) ? "" : entries.get(found).value();
    }

    public static void main(String[] args) {
        TimeMap map = new TimeMap();
        map.set("foo", "bar", 1);
        System.out.println(map.get("foo", 1));
        System.out.println(map.get("foo", 3));
        map.set("foo", "bar2", 4);
        System.out.println(map.get("foo", 4));
        System.out.println(map.get("foo", 5));

        System.out.println("[" + map.get("foo", 0) + "]");      // before the first set
        System.out.println("[" + map.get("baz", 9) + "]");      // a key never set

        map.set("lamp", "off", 2);
        map.set("lamp", "on", 5);
        map.set("lamp", "dim", 9);
        map.set("lamp", "off", 14);
        System.out.println(map.get("lamp", 8) + " " + map.get("lamp", 9)
            + " " + map.get("lamp", 100) + " " + map.get("foo", 100));
    }
}

Running it prints:

Output
bar
bar
bar2
bar2
[]
[]
on dim off bar2

The first four lines answer the example's four get calls in order. The second one is bar, the value from time 1, even though nothing was set at time 3.

The two lines with [] are empty strings, printed between brackets so they can be seen. The first comes from get("foo", 0): no entry is that early, so found stays -1. The second comes from "baz", which was never set, so store.get returns null.

The last line is for "lamp" and the newest values. At time 8 it prints on, the value set at 5, as in the walk-through above. At 9 it prints dim, set at exactly 9. At 100, later than every set, "lamp" gives its newest value off and "foo" gives bar2.

Complexity

Both methods start with one hash lookup for the key; after that, set appends one entry and get runs one binary search over that key's list.

  • set: O(1) amortised, which means on average over many calls. ArrayList.add writes at the end of the list, and only now and then grows the list by copying it into a bigger array.
  • get: O(log k), where k is the number of values stored for that key. Each check halves the part of the list still in play, so a list of k entries takes about log2 k checks.
  • Space: O(number of set calls). Each call adds one Entry to some list, and nothing is ever removed.