Time Based Key Value Store
MediumNeetCode 150 Binary SearchCompassLyftCitadelAxonConfluentFlexportProblem
Build a class TimeMap, a key-value store that remembers when each value was written.
It needs these operations:
TimeMap()creates an empty store.set(key, value, timestamp)records thatkeyhadvalueat timetimestamp.get(key, timestamp)returns the value that was written tokeyat the latest time that is less than or equal totimestamp. If there is no such time, it returns an empty string.
The same key may be written many times. The times passed to set for one key always increase.
The input lists the calls and their arguments; the output lists what each call returns
(null for the constructor and for set).
Constraints
- 1 ≤ key.length, value.length ≤ 100, lowercase letters
- 1 ≤ timestamp ≤ 10⁷
- For one key, set is called with strictly increasing timestamps
- At most 2 · 10⁵ calls in total
Examples: pick one to animate
Solutions
Time: set is one append, O(1). get binary searches one key's list, which has at most n entries.
Space: Every (time, value) pair written by set is stored once.
Keep a list of (time, value) pairs for every key. Because times for a key only increase, the list is
already sorted, so get can binary search it for the last time that is at or before the
asked time, remembering the best value seen along the way.