KatInterview

Reconstruct Versioned Key-Value Store from Operation Log

Data Structure DesignAuto-graded · 15 test cases
MediumAuto-gradedData Structure Designdata structuressimulationversioned store

Last updated

Tests the ability to replay a sequential log of set/delete operations on a key-value store and answer point-in-time value queries efficiently.

Versioned Key-Value Store

You are given a log of operations applied, in order, to an initially empty key-value store. Each operation is one of:

OperationFormatEffect
SET["SET", key, value]Sets key to value at this version
DEL["DEL", key]Deletes key at this version

Operations are numbered 1-indexed (the first operation is version 1, the second is version 2, etc.).

After replaying the full log you receive a list of queries. Each query is [key, version] and asks:

What was the value of key immediately after operation number version was applied?

Rules:

  • If key existed (was SET and not yet DEL-ed) at that version, return its value (always a non-empty string).
  • If key did not exist at that version (never set, or most recently deleted), return None.
  • A DEL on a key that does not exist is a no-op (it still consumes a version number).
  • Version numbers in queries are guaranteed to be between 1 and len(ops) inclusive.

Implement query_versioned_store(ops, queries) which returns a list of answers (strings or None) in the same order as the queries.

Constraints

  • 1 ≤ len(ops) ≤ 2000
  • 1 ≤ len(queries) ≤ 2000
  • Each operation is either ["SET", key, value] or ["DEL", key]
  • All keys and values are non-empty strings consisting of lowercase letters and digits
  • key length ≤ 20, value length ≤ 50
  • Query versions are integers in [1, len(ops)]

Examples

Example 1

Input: query_versioned_store([['SET', 'name', 'alice'], ['SET', 'age', '30'], ['DEL', 'name'], ['SET', 'name', 'bob']], [['name', 1], ['name', 3], ['name', 4], ['age', 2], ['age', 5]])

Output: ['alice', None, 'bob', '30', '30']

Example 2

Input: query_versioned_store([['SET', 'x', '10'], ['DEL', 'x'], ['DEL', 'x'], ['SET', 'x', '20']], [['x', 1], ['x', 2], ['x', 3], ['x', 4]])

Output: ['10', None, None, '20']

Example 3

Input: query_versioned_store([['SET', 'a', '1'], ['SET', 'b', '2'], ['SET', 'a', '3']], [['a', 1], ['a', 2], ['a', 3], ['b', 1], ['b', 3], ['c', 2]])

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

Hints

Hint 1

For each key, keep a sorted list of (version, value_or_sentinel) events so you can binary-search to the right version later.

Hint 2

Use a special sentinel (e.g., None) to record DEL events in the history, so a binary search returns None for deleted keys.

Hint 3

Build the per-key history during a single pass over ops, then answer every query in O(log n) with bisect_right.