Pythonic Implementations of Time Based Key-Val Store
Approach 1: Linear Search
Our first solution is using dictionary. This has a \(O(1)\) complexity for setting and \(O(n)\) for getting, as we have to perform linear search. There are two tricks:
- Extending the
defaultdict
class. - Chaining the
.get(key, {}).items()
expressions to make code looks more elegant.
class TimeMap(defaultdict): |
However, the runtime exceeded limit when testing on LeetCode.
Approach 2: Binary Search
Alternatively, we can put time: val
pairs into list, and use binary search to find them.
class TimeMap(defaultdict): |
Notice that the same trick here is used again. When the list is empty, bisect_right
returns 0
, which again indicates there's not valid query result. With the short circuit evaluation, self[key]
won't be executed either.
Approach 3: Sorted Container
from sortedcontainers import SortedDict |