AlgoInsight

DSA problem

Time Based Key-Value Store

MediumData Structure DesignPattern: Data Structure Designtop300GoogleAmazonMicrosoftCitadelApple

Design a time-based key-value data structure that can store multiple values for the same key at different timestamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class with two methods.

TimeMap() initializes the object of the data structure. set(key, value, timestamp) stores the key key with value value at the given timestamp. get(key, timestamp) returns the value associated with key such that set was called previously with a timestamp_prev <= timestamp. If there are multiple such values, return the value associated with the largest timestamp_prev. If there are no values, return the empty string "".

The crucial observation is that all timestamps passed to set are strictly increasing — this is part of the problem's contract. That means for any single key, the list of (timestamp, value) entries is already sorted by timestamp simply by virtue of insertion order. So set is a constant-time append, and get reduces to a binary search for the largest timestamp not exceeding the query.

The natural backing structure is a hash map from key to a list of (timestamp, value) pairs. set appends to the list in O(1). get runs binary search on that list, finding the rightmost entry with timestamp ≤ query in O(log n). Overall time is O(1) per set and O(log n) per get; space is O(N) for N total set calls. The strictly-monotonic-timestamps constraint is what allows binary search instead of a balanced BST.

Examples

Example 1
Input: ["TimeMap","set","get","get","set","get","get"] [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation: set("foo","bar",1) stores [(1,"bar")]. get("foo",1) returns "bar". get("foo",3) returns "bar" (largest ts <= 3). set("foo","bar2",4) appends to give [(1,"bar"),(4,"bar2")]. get("foo",4) returns "bar2". get("foo",5) returns "bar2".
Example 2
Input: ["TimeMap","set","set","get"] [[],["love","high",10],["love","low",20],["love",5]]
Output: [null,null,null,""]
Explanation: A query timestamp 5 falls before any stored timestamp for "love", so the empty string is returned.
Example 3
Input: ["TimeMap","get"] [[],["nope",1]]
Output: [null,""]
Explanation: Querying an unknown key returns the empty string.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

hash-tablestringbinary-searchdesign

Browse all DSA problems