KatInterview

Time-Versioned Key-Value Storage

Data Structure DesignAuto-graded · 14 test cases
HardAuto-gradedData Structure Designbinary-searchhash-mapdata-structures

Last updated

Implement a data structure that stores versioned values by timestamp and retrieves the most recent version at or before a query time.

Build a time-versioned storage system that records string values for string keys at integer timestamps. The system must handle updates arriving in any order and efficiently answer queries for the current or historical state.

Implement a function time_versioned_store(operations, arguments) that processes a sequence of operations on a versioned store:

  • "LatestValueStore" with []: Initialize or reset the store. Output None.
  • "set" with [key, value, timestamp]: Record that key had value at timestamp. Updates may arrive out of chronological order. If the same (key, timestamp) pair is stored multiple times, the most recent call's value takes precedence. Output None.
  • "get" with [key] or [key, timestamp]: Return the value for key with the largest timestamp that does not exceed timestamp. If timestamp is None or omitted, return the value with the largest timestamp overall. If no qualifying entry exists, return "".

The function receives two parallel lists: operations contains operation names, and arguments contains the corresponding argument lists. Return a list of outputs, one per operation.

Performance matters: with up to 200,000 operations, scanning all history per query will exceed time limits.

Constraints

  • 1 <= len(key), len(value) <= 50
  • key and value contain only lowercase letters, digits, and underscores
  • 1 <= timestamp <= 10^9
  • At most 2 * 10^5 total operations
  • Updates can arrive in arbitrary timestamp order

Examples

Example 1

Input: time_versioned_store(['LatestValueStore', 'set', 'set', 'set', 'get', 'get', 'get', 'get'], [[], ['device_1', 'standby', 10], ['device_1', 'active', 20], ['device_1', 'idle', 5], ['device_1'], ['device_1', 15], ['device_1', 4], ['device_2']])

Output: [None, None, None, None, 'active', 'standby', '', '']

Example 2

Input: time_versioned_store(['LatestValueStore', 'set', 'set', 'set', 'get', 'get', 'get'], [[], ['status', 'yellow', 100], ['status', 'red', 100], ['status', 'green', 50], ['status', 100], ['status'], ['status', 75]])

Output: [None, None, None, None, 'red', 'red', 'green']

Hints

Hint 1

For each key, maintain its timeline in a structure that supports efficient predecessor queries—finding the largest timestamp not exceeding a target value.

Hint 2

Binary search can locate the correct version in logarithmic time if timestamps are kept sorted. Consider how to maintain sorted order as new timestamps arrive.

Hint 3

When the same (key, timestamp) pair is updated twice, only the storage value needs updating—avoid duplicating the timestamp in your sorted structure.