#981

Time Based Key-Value Store

Medium
Hash TableStringBinary SearchDesignHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(n)
💡

Intuition

Time O(log n)Space O(n)

The optimal solution uses a dictionary to map keys to a list of timestamps and values. This allows us to perform binary search on the timestamps for efficient retrieval, reducing the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a dictionary to store keys, where each key maps to a list of tuples containing (timestamp, value).
  2. 2Step 2: For the 'set' operation, append the (timestamp, value) pair to the list for the given key.
  3. 3Step 3: For the 'get' operation, use binary search to find the largest timestamp less than or equal to the requested timestamp.
solution.py16 lines
1from collections import defaultdict
2import bisect
3
4class TimeMap:
5    def __init__(self):
6        self.store = defaultdict(list)
7
8    def set(self, key: str, value: str, timestamp: int) -> None:
9        self.store[key].append((timestamp, value))
10
11    def get(self, key: str, timestamp: int) -> str:
12        if key not in self.store:
13            return ""
14        values = self.store[key]
15        i = bisect.bisect_right(values, (timestamp,)) - 1
16        return values[i][1] if i >= 0 else ""

Complexity note: The time complexity is O(log n) for the 'get' operation due to the binary search on the list of timestamps, while the 'set' operation is O(1) as we simply append to the list.

  • 1Using binary search significantly optimizes retrieval time.
  • 2Storing timestamps alongside values allows for efficient access to the most recent value.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.