KatInterview

Versioned Key-Value Store with Global Version Tracking

Data Structure DesignAuto-graded · 19 test cases
MediumAuto-gradedData Structure Designbinary-searchdata-structuresversioning

Last updated

Implement a key-value store where each write increments a global version counter and reads retrieve values by version using binary search.

Build a key-value store that maintains a global version number incremented with every write operation. The store supports two operations:

Set Operation: set(key, value) writes a value to a key, assigns it the next available global version number (starting from 1), and returns that version number.

Get Operation: get(key, version) retrieves the value that was most recently written to the key at or before the specified version. If no value has been written to the key at or before that version, return None.

You are given a sequence of operations to process. Each operation is either a set or get, with corresponding arguments. Return a list containing the result of each operation: for set operations, return the assigned version number; for get operations, return the retrieved value or None.

Important details:

  • The global version counter starts at 1 and increments by 1 with each set operation
  • Each key maintains its own sparse history of (version, value) pairs
  • A get(key, version) finds the write with the largest version number ≤ the requested version
  • If a key has never been written, or if all writes to that key occurred after the requested version, return None

Constraints

  • 1 ≤ number of operations ≤ 10^5
  • Keys are non-empty strings
  • Values are integers
  • Version numbers in get operations are positive integers
  • All operations must be processed in order

Examples

Example 1

Input: versioned_kv_store(['set', 'set', 'get', 'get', 'get'], [['a', 10], ['b', 20], ['a', 1], ['a', 2], ['b', 1]])

Output: [1, 2, 10, 10, None]

Example 2

Input: versioned_kv_store(['get', 'set', 'get', 'set', 'get', 'get'], [['missing', 1], ['x', 7], ['x', 1], ['x', 9], ['x', 2], ['x', 99]])

Output: [None, 1, 7, 2, 9, 9]

Example 3

Input: versioned_kv_store(['set', 'set', 'set', 'get', 'get', 'get'], [['k', 1], ['k', 2], ['k', 3], ['k', 2], ['k', 3], ['k', 100]])

Output: [1, 2, 3, 2, 3, 3]

Hints

Hint 1

Each key needs to store a chronological list of (version, value) pairs as writes occur.

Hint 2

For a get operation, you need to find the rightmost version in the key's history that doesn't exceed the requested version.

Hint 3

Binary search can efficiently locate the correct historical entry if you search on the version numbers.