AlgoMaster Logo

Time Based Key-Value Store

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Using HashMap with Linear Search (Basic)

Intuition:

The simplest approach to solve this problem is to use a HashMap where the keys are strings and the values are lists of pairs (timestamp, value). To perform the get operation, we can iterate over the list for a particular key and find the largest timestamp that is less than or equal to the given timestamp.

Steps:

  1. We'll use a HashMap<String, List<Pair<Integer, String>>> to store keys with their associated timestamp-value pairs.
  2. For the set operation, we'll add a pair of (timestamp, value) to the list corresponding to the key.
  3. For the get operation, we'll iterate through the list associated with the given key and check for the largest timestamp that is less than or equal to the given timestamp.

Code:

2. Using HashMap with Binary Search (Optimal)

Intuition:

An optimized approach improves the get operation by using binary search. Given that the timestamps are stored in sorted order by insertion, we can utilize binary search to quickly locate the largest timestamp that is less than or equal to the given timestamp.

Steps:

  1. Similar to the previous approach, we'll use a HashMap with lists of pairs for each key.
  2. For the set operation, the implementation remains the same.
  3. For the get operation, use binary search on the list of pairs for the given key instead of linear search.

Code: