LeetCode solutions

1023. Time Based Key-Value Store

My accepted Python solution to LeetCode problem 1023, Time Based Key-Value Store, running in 136ms.

  • Difficulty: Medium
  • Python
  • Runtime 136ms
  • Memory 73.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 136ms, memory 73.1MB, accepted 2026-01-02.

python
class TimeMap:

    def __init__(self):
        self.store = {}  # key -> [(timestamp, value), ...]

    def set(self, key: str, value: str, timestamp: int) -> None:
        if key not in self.store:
            self.store[key] = []
        self.store[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        if key not in self.store:
            return ""
        
        values = self.store[key]
        
        # Binary search for largest timestamp <= given timestamp
        left, right = 0, len(values) - 1
        result = ""
        
        while left <= right:
            mid = (left + right) // 2
            if values[mid][0] <= timestamp:
                result = values[mid][1]
                left = mid + 1
            else:
                right = mid - 1
        
        return result


# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)

Source