Leetcode 981: Time Based Key-Value Store

grid47
grid47
Exploring patterns and algorithms
Jul 31, 2024 7 min read

Design a time-based key-value data structure that stores multiple values for the same key at different timestamps and supports retrieving the value at a specific timestamp.
Problem
Approach
Steps
Complexity
Input: The input consists of a series of `set` and `get` operations on a `TimeMap` object.
Example: ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["user1", "apple", 1], ["user1", 1], ["user1", 3], ["user1", "banana", 4], ["user1", 4], ["user1", 5]]
Constraints:
• 1 <= key.length, value.length <= 100
• key and value consist of lowercase English letters and digits.
• 1 <= timestamp <= 10^7
• All timestamps for `set` calls are strictly increasing.
• At most 2 * 10^5 calls will be made to `set` and `get`.
Output: For each `get` operation, return the value corresponding to the key at or before the given timestamp, or an empty string if no such value exists.
Example: [null, null, "apple", "apple", null, "banana", "banana"]
Constraints:
• The output for each `get` operation should be a string.
Goal: Implement a time-based key-value store with efficient retrieval for a given timestamp.
Steps:
• Use a map to store key-value pairs along with timestamps.
• For each `set` operation, append the timestamp and value pair to the list of values for the given key.
• For each `get` operation, perform binary search to find the value with the largest timestamp less than or equal to the given timestamp.
Goal: The number of operations should be efficient enough to handle up to 2 * 10^5 calls.
Steps:
• 1 <= key.length, value.length <= 100
• key and value consist of lowercase English letters and digits.
• 1 <= timestamp <= 10^7
• All timestamps for `set` calls are strictly increasing.
• At most 2 * 10^5 calls will be made to `set` and `get`.
Assumptions:
• The data structure supports efficient insertion and retrieval operations.
Input: ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["user1", "apple", 1], ["user1", 1], ["user1", 3], ["user1", "banana", 4], ["user1", 4], ["user1", 5]]
Explanation: The example demonstrates the behavior of the `TimeMap` class, where values are stored with timestamps and can be retrieved by the closest timestamp at or before a given time.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus