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 TimeMapset(key, value, timestamp)valuekeytimestampget(key, timestamp)keytimestamp""set
Example
get("foo", 1) returns "bar"
get("foo", 3) returns "bar"
set("foo", "bar2", 4)
get("foo", 4) returns "bar2"
get("foo", 5) returns "bar2"
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
Look at the example. "foo""bar""bar2"get("foo", 4)get("foo", 3)
It returns "bar""bar""bar2"getset
On the time line at the top, "bar""bar2"get("foo", 3)"bar"get("foo", 0)""
The bottom row, the list for "foo"(1, "bar")(4, "bar2")get
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
Where each key's history is kept
Where does the class keep the values? In a HashMaprecord
Keeping each history in time order
Does a list ever need sorting? No. Timestamps passed to setset
Finding the last entry at or before a time
How does get
Binary search keeps two positions, lohifound"lamp"(2, "off")(5, "on")(9, "dim")(14, "off")get("lamp", 8)lohi
The middle position is 1, with timestamp 5. That is <= 8, a yes, so foundlohilohi"on"
foundget""
Optional: a TreeMap per key
Is there a ready-made way? A TreeMapTreeMap<Integer, String>floorEntry(timestamp)nullArrayList
Java Solution
The class has four parts, one for each piece of the approach:
: a record holding one timestamp with its value.Entry : thestore from each key to its list of entries, oldest first.HashMap : appends a newset to the key's list.Entry creates the list the first time a key is set.computeIfAbsent : binary searches the key's list for the last entry with a timestamp <= the given time, and returnsget for a key that was never set or when"" stays -1.found
The main"foo""lamp"
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:
bar
bar
bar2
bar2
[]
[]
on dim off bar2
The first four lines answer the example's four getbar
The two lines with []get("foo", 0)found"baz"store.getnull
The last line is for "lamp"ondim"lamp"off"foo"bar2
Complexity
Both methods start with one hash lookup for the key; after that, setget
- set: O(1) amortised, which means on average over many calls.
writes at the end of the list, and only now and then grows the list by copying it into a bigger array.ArrayList.add - 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
to some list, and nothing is ever removed.Entry