Time Based Key Value Store

Program for Time Based Key-Value Store Problem

Design a time-based key-value store that can:

  • Store multiple values for the same key at different timestamps.
  • Retrieve a key’s value based on a given timestamp.
Time Based Key value

Constraints:

  • 1 <= key.length, value.length <= 100
  • key and value only include lowercase English letters and digits.
  • 1 <= timestamp <= 1000

Program for Time Based Key-Value Store Solution

Recommendation for Time and Space Complexity – You should aim for a solution with O(1) time for set(), O(logn) time for get(), and O(m * n) space, where n is the total number of values associated with a key, and m is the total number of keys.

Hints for solving problems

Hint 1 :

Can you think of a data structure that is useful for storing key-value pairs? Perhaps a hash-based data structure where we not only store unique elements but also associate additional information with each element?

Hint 2 :

We store key-value pairs in a hash map. In this case, we store the keys as usual, but instead of a single value, we store a list of values, each paired with its corresponding timestamp. This allows us to implement the set() method in O(1). How can you leverage this hash map to implement the get() method?

There are mainly 2 approach to solve this problem-

  1. Brute Force Method
  2. Binary Search(Sorted Map) Method

1. Brute Force Method

Store all key-value pairs with timestamps and iterate through the list to find the most recent valid timestamp for a given key, resulting in O(n) lookup time.

  • Time complexity: O(1) for set() and O(n) for get().
  • Space complexity: O(m∗n)

where n is the total number of unique timestamps associated with a key and m is the total number of keys.

Code

2. Binary Search (Sorted Map) Method

Use a sorted map to store values for each key, with timestamps as the keys in the map. To retrieve a value, perform a binary search on the timestamps to find the largest timestamp less than or equal to the given one. This method is efficient with O(log n) retrieval time.

  • Time complexity: O(1) for set() and O(log n) for get().
  • Space complexity: O(m∗n)

where n is the total number of unique timestamps associated with a key and m is the total number of keys.

Code

More Articles