Time Based Key-Value Store - Problem
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the TimeMap class:
TimeMap()Initializes the object of the data structure.void set(String key, String value, int timestamp)Stores the keykeywith the valuevalueat the given timetimestamp.String get(String key, int timestamp)Returns a value such thatsetwas called previously, withtimestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largesttimestamp_prev. If there are no values, it returns"".
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["TimeMap", "set", "get", "get", "set", "get", "get"], parameters = [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
›
Output:
[null, null, "bar", "bar", null, "bar2", "bar2"]
💡 Note:
TimeMap created → set foo=bar at t=1 → get foo at t=1 returns "bar" → get foo at t=3 returns "bar" (t=1 ≤ 3) → set foo=bar2 at t=4 → get foo at t=4 returns "bar2" → get foo at t=5 returns "bar2" (t=4 ≤ 5)
Example 2 — No Valid Timestamp
$
Input:
operations = ["TimeMap", "set", "get"], parameters = [[], ["love", "high", 10], ["love", 5]]
›
Output:
[null, null, ""]
💡 Note:
TimeMap created → set love=high at t=10 → get love at t=5 returns "" because no timestamp ≤ 5 exists
Example 3 — Multiple Values Same Key
$
Input:
operations = ["TimeMap", "set", "set", "get"], parameters = [[], ["key", "val1", 1], ["key", "val2", 3], ["key", 2]]
›
Output:
[null, null, null, "val1"]
💡 Note:
TimeMap created → set key=val1 at t=1 → set key=val2 at t=3 → get key at t=2 returns "val1" (largest timestamp ≤ 2 is 1)
Constraints
- 1 ≤ key.length, value.length ≤ 100
- key and value consist of lowercase English letters and digits.
- 1 ≤ timestamp ≤ 107
- All the timestamps of set are strictly increasing.
- At most 2 × 105 calls will be made to set and get.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Operations: set("foo", "bar", 1), get("foo", 3)
2
Process
Store values with timestamps, find largest timestamp ≤ query
3
Output
Return corresponding value: "bar"
Key Takeaway
🎯 Key Insight: Combine HashMap for key lookup with sorted arrays and binary search for timestamp queries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code