KatInterview

Historical Key-Value Store with Time-Based Retrieval

Data Structure DesignAuto-graded · 13 test cases
MediumAuto-gradedData Structure Designbinary-searchhash-mapdata-structures

Last updated

Tests your ability to build a versioned data store supporting efficient historical lookups through binary search on sorted timestamps.

Build a versioned key-value store that records entries along with their timestamps and retrieves historical values efficiently.

Your task is to implement a function that processes a sequence of operations on this store:

  • "TimeMap": Initialize or reset the store to an empty state.
  • "set": Record a key-value pair along with a timestamp.
  • "get": Retrieve the most recent value for a key that was recorded at or before a given timestamp.

The function receives two parallel lists:

  • operations: a list of operation names
  • arguments: a list of argument lists, one per operation

Return a list of outputs, one per operation:

  • "TimeMap" and "set" operations return None
  • "get" operations return a string

For a "get" query with a given key and timestamp t, return the value associated with the largest timestamp that is less than or equal to t. If no such entry exists (either the key was never recorded, or all its timestamps exceed t), return an empty string "".

Important guarantee: For any single key, all "set" operations arrive with strictly increasing timestamps.

Constraints

  • 1 <= key.length, value.length <= 100
  • 1 <= timestamp <= 10^7
  • Timestamps for each individual key are strictly increasing across "set" operations
  • At most 2 * 10^5 total operations will be processed
  • Keys and values contain only alphanumeric characters

Examples

Example 1

Input: historical_store(['TimeMap', 'set', 'get', 'get', 'set', 'get', 'get'], [[], ['foo', 'bar', 1], ['foo', 1], ['foo', 3], ['foo', 'bar2', 4], ['foo', 4], ['foo', 5]])

Output: [None, None, 'bar', 'bar', None, 'bar2', 'bar2']

Hints

Hint 1

Since timestamps arrive in increasing order for each key, you can maintain them in a sorted list without explicit sorting

Hint 2

Use binary search to quickly locate the largest timestamp that doesn't exceed your query timestamp

Hint 3

Maintain parallel arrays: one for timestamps and one for values, both indexed identically for each key