Skip to main content
Back to problems
#981
Medium Algorithms

Time based key value store

Hash Table String Binary Search Design
49.7% acceptance
Feb 22, 2026
5246
728
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the TimeMap class: TimeMap() Initializes the object of the data structure. void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp. String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".

Solution

Rust
Time O(log n)
Space O(n)
LeetCode
solution.rs
* impl TimeMap {

 *     fn new() -> Self {

 *     }

 *     fn set(&self, key: String, value: String, timestamp: i32) {

 *     }

 *     fn get(&self, key: String, timestamp: i32) -> String {

 *     }
 * }
 */

/**
 * Your TimeMap object will be instantiated and called as such:
 * let obj = TimeMap::new();
 * obj.set(key, value, timestamp);
 * let ret_2: String = obj.get(key, timestamp);
 */

use std::collections::HashMap;
pub struct TimeMap {
  map: HashMap<String, Vec<(i32, String)>>,
}
impl TimeMap {
  pub fn new() -> Self { TimeMap { map: HashMap::new() } }
  pub fn set(&mut self, key: String, value: String, timestamp: i32) {
    self.map.entry(key).or_default().push((timestamp, value));
  }
  pub fn get(&self, key: String, timestamp: i32) -> String {
    match self.map.get(&key) {
      None => String::new(),
      Some(v) => {
        match v.binary_search_by_key(&timestamp, |&(t, _)| t) {
          Ok(i) => v[i].1.clone(),
          Err(0) => String::new(),
          Err(i) => v[i-1].1.clone(),
        }
      }
    }
  }
}