[Programming Problem] Time Based Key-Value Store

Create a timebased key-value store class TimeMap, that supports two operations.

  1. set(string key, string value, int timestamp)
    Stores the key and value, along with the given timestamp.
  2. get(string key, int timestamp)
    Returns a value such that set(key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the one with the largest timestamp_prev. If there are no values, it returns the empty string ("").

[Problem Link]

Note that key-values are inserted in timestamp order (meaning when we set multiple values for a key, we wont request timestamp 10 before timestamp 1-9). So, the timestamp’s for a key will be in sorted order.

The problem essentially boils down to running a binary search for a target (or next smallest target). At every step, we return value if it matches exactly, otherwise go left or right. When we get a return from the recursion, we have a choice between returning a.) returned value or b.) current (mid) value. We return the one lower than target. If both values are lower than target, we return the one closer to target.

/**
 * Initialize your data structure here.
 */
 
var closest = function(i, j, arr, val) {
    if ( i > j ) return {value: '', timestamp: Number.MAX_VALUE};
 
    let mid = i + Math.round((j-i)/2);
    if ( arr[mid].timestamp === val ) return arr[mid];
 
    let ret = Number.MAX_VALUE;
    if ( arr[mid].timestamp > val )
        ret = closest(i, mid-1, arr, val);
    else 
        ret = closest(mid+1, j, arr, val);
 
    if ( arr[mid].timestamp < val && ret.timestamp < val ) {
        return arr[mid].timestamp > val ? arr[mid] : ret;
    } else if ( arr[mid].timestamp < val ) {
        return arr[mid];
    } else {
        return ret;
    }
}
 
 
var TimeMap = function() {
    this.map = {};
};
 
/** 
 * @param {string} key 
 * @param {string} value 
 * @param {number} timestamp
 * @return {void}
 */
TimeMap.prototype.set = function(key, value, timestamp) {
    if (!this.map[key]) this.map[key] = [];
    this.map[key].push({value, timestamp});
};
 
/** 
 * @param {string} key 
 * @param {number} timestamp
 * @return {string}
 */
TimeMap.prototype.get = function(key, timestamp) {
    if (!this.map[key]) return "";
    let arr = this.map[key];
    let ret = closest(0, arr.length-1, arr, timestamp);
    return ret.value;
};
 
/** 
 * Your TimeMap object will be instantiated and called as such:
 * var obj = new TimeMap()
 * obj.set(key,value,timestamp)
 * var param_2 = obj.get(key,timestamp)
 */

10 thoughts on “[Programming Problem] Time Based Key-Value Store

Leave a Reply

Your email address will not be published. Required fields are marked *