981. Time Based Key-Value Store
Problem description:
Create a timebased key-value store class TimeMap
, that supports two operations.
set(string key, string value, int timestamp)
- Stores the
key
andvalue
, along with the giventimestamp
.
get(string key, int timestamp)
- Returns a value such that
set(key, value, timestamp_prev)
was called previously, withtimestamp_prev <= timestamp
. - If there are multiple such values, it returns the one with the largest
timestamp_prev
. - If there are no values, it returns the empty string (
""
).
Example 1:
1 | Input:inputs = ["TimeMap","set","get","get","set","get","get"], inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]] |
Example 2:
1 | Input:inputs = ["TimeMap","set","set","get","get","get","get","get"], inputs = [[],["love","high",10],["love","low",20],["love",5],["love",10],["love",15],["love",20],["love",25]] |
Note:
- All key/value strings are lowercase.
- All key/value strings have length in the range
[1, 100]
- The
timestamps
for allTimeMap.set
operations are strictly increasing. 1 <= timestamp <= 10^7
TimeMap.set
andTimeMap.get
functions will be called a total of120000
times (combined) per test case.
Solution:
For this kind of key-value pair, using dictionary would help us find item in shortest time.
However, this question have several timestamp we need to consider. We could use a list to store all the timestamp-value
.
- Notice in Note 3, the timestamp is strictly increasing. So we don’t have to sort the element in list before searching
In get()
, we could use bisect_right
or write own binary search to find the value that is greater than timestamp
. The reason we’re finding greater
than timestamp
is because we use right
as boundary, then we could return nums[right-1]
as it’s the value that smaller than timestamp
but closest to timestamp
.
For example:1
2
3nums: [5,10,15,20,25], timestamp: 8
at the last round, right would be idx:1, nums[1] = 10
then we return nums[right-1] = nums[0], as it's the one smaller than 8 but fulfilled timestamp_prev <= timestamp.
1 | class TimeMap: |
1 | class TimeMap: |
time complexity:
- set(): $O(1)$ for single operation, $O(n)$ for total. Note: assuming timestamps are only increasing. If not, it’s $O(n log n)$.
- get(): $O(logn)$,
n
is length of list innums[key]
, and total O(m log n),m
is number ofget()
request.
space complexity: $O(n)$
reference:
related problem: