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 key key with the value value at the given time timestamp.
  • String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_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
Time-Based Key-Value Store: Store and Retrieve with Timestampsset("foo", "bar", 1)Store value with timestampHashMap: "foo" → [(1, "bar")]Sorted by timestampget("foo", 3)Find value at timestamp ≤ 3Binary Search: 1 ≤ 3 ✓Return "bar"Result: "bar"
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
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
185.0K Views
High Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen