NeetCode #287LC-981MediumBinary SearchNC 150NC 250
← Back to All Problems#287 · #981 · Time Based Key-Value Store(基于时间的键值存储)
📌 Problem Statement & Constraints
Design a time-based key-value store supporting
set(key, value, timestamp) and get(key, timestamp), which returns the value with the largest timestamp less than or equal to the given one, or an empty string. Timestamps for the same key are strictly increasing across set calls. Constraints: at most 2 * 10^5 calls.💡 Core Algorithmic Approaches
- For each key, keep two parallel lists: the timestamps in increasing order and the corresponding values.
- Because
setcalls arrive in increasing timestamp order per key, the lists are already sorted -- no explicit sort is needed. getis then abisect_righton the timestamp list: the index just before the insertion point holds the answer.- This gives O(log n) per
getand O(1) perset.
💻 Benchmark Python3 Implementation
class TimeMap:
def __init__(self):
from collections import defaultdict
self.times = defaultdict(list) # key -> increasing timestamps
self.vals = defaultdict(list) # key -> values aligned with times
def set(self, key: str, value: str, timestamp: int) -> None:
self.times[key].append(timestamp) # timestamps arrive increasing
self.vals[key].append(value)
def get(self, key: str, timestamp: int) -> str:
from bisect import bisect_right
arr = self.times.get(key)
if not arr:
return ""
i = bisect_right(arr, timestamp) # first index with time > timestamp
return self.vals[key][i - 1] if i > 0 else ""⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) per set (amortised append) and O(log n) per get.
💾 Space Complexity
O(total number of stored pairs).
⚠️ Interview Pitfalls & Follow-ups
- Sorting the timestamps on every
set: they already arrive in increasing order per key, so sorting is wasted work. - Using
bisect_left: that finds the first index withtime >= timestamp; you want the largest time<= timestamp, hencebisect_rightminus one. - Forgetting the
i == 0guard: it means no stored timestamp is at or before the query, so the answer is the empty string. - Storing
(timestamp, value)tuples in one list and using a sentinel for bisection: workable but error-prone; parallel lists are simpler.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
基于时间的键值存储
设计一个基于时间的键值数据结构,该结构可以在不同时间戳存储对应同一个键的多个值,并检索特定时间戳对应的值。实现 TimeMap 类: set(key, value, timestamp) 存储键值对及时间戳; get(key, timestamp) 返回在给定时间戳下 key 对应的值,若不存在则返回空字符串 "" 。所有 set 调用中的时间戳严格递增; get 查询的时间戳不一定存在。约束:1 ≤ key.length, value.length ≤ 100;1 ≤ timestamp ≤ 10^7;最多调用 2 × 10^5 次方法。
核心要点
- 哈希表 + 有序列表(标准解) : store[key] 是一个列表,按时间戳升序保存 (timestamp, value) 。
- 为什么天然有序 :题目保证 set 的时间戳严格递增,因此直接 append 即可保持有序,无需排序。
- get 用二分找「时间戳 ≤ 查询时间戳」的最大值 :用「记录最后一次可行答案」的二分模板。
- 为什么不能用普通二分直接返回 :因为查询的时间戳可能不存在于列表中,需要找到「不超过它的最大时间戳」对应的值。
常见陷阱
- 用普通二分(找到即返回) :查询的时间戳可能不存在,必须找「≤ 目标的最大时间戳」,因此需要「记录可行答案 + 继续向右」的模板。
- 对列表排序 :题目保证时间戳递增,无需排序;排序反而是 O(m log m) 的无用开销。
- key 不存在时抛 KeyError :应返回空字符串。用 .get(key) 或 defaultdict 配合判空。
- 把值也存成时间戳索引 :直接存 (timestamp, value) 元组最简单。
参考实现
from collections import defaultdict
class TimeMap:
def __init__(self):
self.store = defaultdict(list) # key -> [(timestamp, value)]
def set(self, key: str, value: str, timestamp: int) -> None:
self.store[key].append((timestamp, value)) # 时间戳严格递增,天然有序
def get(self, key: str, timestamp: int) -> str:
arr = self.store.get(key)
if not arr:
return ''
lo, hi = 0, len(arr) - 1
res = ''
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid][0] <= timestamp:
res = arr[mid][1] # 记录当前可行答案
lo = mid + 1 # 尝试更大的时间戳
else:
hi = mid - 1
return res