Algo-Sim › Binary Search

Time Based Key-Value Store

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Store each key’s values in timestamp order and binary search for the last timestamp ≤ the query: an upper-bound search on a list that sorts itself.

Problem

Design TimeMap: set(key, value, timestamp) stores the value at that time, and get(key, timestamp) returns the value set for the key at the largest stored timestamp ≤ timestamp, or "" if there is none. Timestamps passed to set are strictly increasing.

Constraints

Edge cases to test

Follow-up questions

Why does the list stay sorted with no sorting?
Timestamps for set are strictly increasing, so appending keeps each list in order: O(1) set, O(log n) get.
What if timestamps can arrive out of order?
Keep a sorted map per key (TreeMap.floorEntry, bisect on a SortedList): O(log n) for both operations.

Solution

Java

class TimeMap {
    private final Map<String, List<Integer>> times = new HashMap<>();
    private final Map<String, List<String>> values = new HashMap<>();

    public void set(String key, String value, int timestamp) {
        // Timestamps arrive in increasing order, so each list stays sorted.
        times.computeIfAbsent(key, k -> new ArrayList<>()).add(timestamp);
        values.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
    }

    public String get(String key, int timestamp) {
        List<Integer> ts = times.getOrDefault(key, new ArrayList<>());
        int lo = 0, hi = ts.size() - 1;
        String result = "";
        while (lo <= hi) {
            int mid = (lo + hi) >>> 1;
            if (ts.get(mid) <= timestamp) {
                result = values.get(key).get(mid);
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return result;
    }
}

Python

from collections import defaultdict


class TimeMap:
    def __init__(self):
        self.store = defaultdict(list)  # key -> [(timestamp, value)]

    def set(self, key, value, timestamp):
        # Timestamps arrive in increasing order, so each list stays sorted.
        self.store[key].append((timestamp, value))

    def get(self, key, timestamp):
        pairs = self.store[key]
        lo, hi = 0, len(pairs) - 1
        result = ""
        while lo <= hi:
            mid = (lo + hi) // 2
            if pairs[mid][0] <= timestamp:
                result = pairs[mid][1]
                lo = mid + 1
            else:
                hi = mid - 1
        return result

C++

#include <bits/stdc++.h>
using namespace std;

class TimeMap {
  public:
    unordered_map<string, vector<int>> times = {};
    unordered_map<string, vector<string>> values = {};

    void set(string &key, string &value, int timestamp) {
        // Timestamps arrive in increasing order, so each list stays sorted.
        times[key].push_back(timestamp);
        values[key].push_back(value);
    }

    string get(string &key, int timestamp) {
        vector<int> ts = times[key];
        int lo = 0, hi = int(ts.size()) - 1;
        string result = "";
        while (lo <= hi) {
            int mid = (lo + hi) >> 1;
            if (ts[mid] <= timestamp) {
                result = values[key][mid];
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return result;
    }
};

More Binary Search problems