↓Skip to main content
  1. LeetCode/

LeetCode 981: Time Based Key-Value Store

·2 mins· ·
LeetCode Medium Hash-Table String Binary-Search Design
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-28

  • Submissions: Runtime Error ×4 → Time Limit Exceeded ×2 → Runtime Error → Time Limit Exceeded → Wrong Answer → Time Limit Exceeded ×2 → Runtime Error → Time Limit Exceeded ×2 → Wrong Answer → Time Limit Exceeded ×2 → Output Limit Exceeded → Time Limit Exceeded ×3 → Runtime Error → Output Limit Exceeded → Wrong Answer → Time Limit Exceeded ×2 → Runtime Error → Time Limit Exceeded → Accepted → Wrong Answer → Runtime Error → Accepted ×2

Approach
#

set timestamps are strictly increasing, so each key’s list is already sorted (Binary Search Template 1). get wants the last timestamp <= t, which is the first position > t minus one, found with bisect_right. A missing key or no match returns the empty string.

My Attempts
#

This took 33 submissions:

  • The binary search wrote l += 1 / r -= 1, moving one step at a time, effectively linear, and kept hitting TLE.
  • get on an unseen key used self.map[key] directly: KeyError.
  • Tuples were stored as (timestamp, value) but read as (value, timestamp); a few versions left debug prints in and hit Output Limit Exceeded.

Solution
#

class TimeMap:
    def __init__(self):
        self.times = defaultdict(list)
        self.values = defaultdict(list)

    def set(self, key: str, value: str, timestamp: int) -> None:
        self.times[key].append(timestamp)
        self.values[key].append(value)

    def get(self, key: str, timestamp: int) -> str:
        i = bisect.bisect_right(self.times[key], timestamp)
        return self.values[key][i - 1] if i else ""

Complexity
#

set is O(1), get is O(log n), space O(n).

Mistakes to Avoid
#

  • get on an unseen key returns the empty string, not KeyError.
  • Binary search must jump (l = mid + 1); moving one step at a time (l += 1) degrades to linear and TLEs.

Interview Explanation
#

Timestamps increase, so each key keeps a list of timestamps and values, and get uses bisect_right to find the last one not after the query. set is O(1), get is O(log n).

Related

LeetCode 424: Longest Repeating Character Replacement
·2 mins
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 note: a variable sliding window where window length minus the top character count is the number of replacements; shrink when it exceeds k
LeetCode 49: Group Anagrams
·2 mins
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 note: use each string’s sorted form as a key; strings sharing a key form one anagram group
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list
LeetCode 153: Find Minimum in Rotated Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 153 note: compare mid with the right end: nums[mid] > nums[r] puts the minimum to the right, otherwise mid may be it, so r = mid
LeetCode 875: Koko Eating Bananas
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 875 note: binary search the speed for the smallest k with total hours <= h, continuing left even when the hours equal h
LeetCode 128: Longest Consecutive Sequence
·2 mins
LeetCode Medium Array Hash-Table Union-Find
LeetCode 128 note: put everything in a set and count upward only from values whose x - 1 is absent; each value is seen at most twice, O(n)