sagelearnai

Time Based Key-Value Store

Difficulty: Medium · Pattern: Binary Search · LeetCode #981

Design TimeMap:

  • set(key, value, timestamp) stores the value at that time (timestamps for a key strictly increase across calls).
  • get(key, timestamp) returns the value with the largest timestamp ≤ timestamp, or "" if none.

Example

text
set("foo","bar",1); get("foo",1) → "bar"; get("foo",3) → "bar"
set("foo","bar2",4); get("foo",4) → "bar2"; get("foo",5) → "bar2"

Hints

  1. Timestamps arrive in increasing order, so each key's list is already sorted.
  2. get is a "floor" binary search.

Approach

Map each key to two parallel lists (timestamps, values), appended in order. For get, binary search for the last timestamp ≤ the query (upper bound − 1); return its value or "". set is O(1), get is O(log n).

Complexity

Time: O(1) set, O(log n) get. Space: O(n).

Python solution
from bisect import bisect_right
from collections import defaultdict

class TimeMap:
    def __init__(self):
        self.ts = defaultdict(list)
        self.vals = defaultdict(list)

    def set(self, key, value, timestamp):
        self.ts[key].append(timestamp)
        self.vals[key].append(value)

    def get(self, key, timestamp):
        i = bisect_right(self.ts[key], timestamp) - 1
        return self.vals[key][i] if i >= 0 else ""
JavaScript solution
class TimeMap {
  constructor() { this.m = new Map(); }
  set(key, value, timestamp) { if (!this.m.has(key)) this.m.set(key, []); this.m.get(key).push([timestamp, value]); }
  get(key, timestamp) {
    const a = this.m.get(key) || []; let lo = 0, hi = a.length;
    while (lo < hi) { const mid = (lo + hi) >> 1; if (a[mid][0] <= timestamp) lo = mid + 1; else hi = mid; }
    return lo ? a[lo - 1][1] : '';
  }
}