THN Interview Prep

981. Time Based Key-Value Store

At a Glance

  • Topic: Hash Table
  • Pattern: Analyze Pattern
  • Difficulty: Medium
  • LeetCode: 981

Problem Statement

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 &quot;&quot;.

Example 1:

Input ["TimeMap", "set", "get", "get", "set", "get", "get"] [[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]] Output [null, null, &q...

Approach & Solution Steps

  • Brute forceO(n) get — scan all pairs for key.
  • Better — map key → list + linear scan from end — O(k) per get for k events of key.
  • OptimalO(log k) get, O(1) amortized set — hash map of append-only vectors + upper-bound style BS for last ≤ timestamp.

Optimal JS Solution

class TimeMap {
	constructor() {
		this.data = new Map();
	}

	set(key, value, timestamp) {
		if (!this.data.has(key)) {
			this.data.set(key, []);
		}
		this.data.get(key).push({ timestamp, value });
	}

	get(key, timestamp) {
		const pairs = this.data.get(key);
		if (!pairs || pairs.length === 0) {
			return '';
		}
		let left = 0;
		let right = pairs.length - 1;
		let best = -1;
		while (left <= right) {
			const mid = left + Math.floor((right - left) / 2);
			if (pairs[mid].timestamp <= timestamp) {
				best = mid;
				left = mid + 1;
			} else {
				right = mid - 1;
			}
		}
		return best === -1 ? '' : pairs[best].value;
	}
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page