KatInterview

Layered Scopes for a Key-Value Store with Savepoints

Data Structure DesignModel answer
EasyModel answerData Structure Designstackhash-mapdesign

Last updated

Build an in-memory key-value store whose writes can be grouped into nested, revertable scopes that either merge into the enclosing scope or are thrown away.

Nested Scopes in a Key-Value Store

Implement a small in-memory key-value store in which writes can be grouped into nested transactions. Keys are strings and values are integers.

The store exposes these operations:

  • set(key, value): Records a value for key. If a transaction is open, the write belongs to the innermost open transaction. Otherwise it goes straight into the base store.
  • get(key): Returns the value currently visible for key. The innermost transaction that wrote the key takes precedence, then the enclosing ones, and finally the base store.
  • begin(): Opens a new transaction nested inside the current one (or directly on the base store if none is open). Calls to begin() can be repeated to any depth.
  • rollback(): Throws away every write made in the innermost open transaction and closes it. The state returns to what it was just before the matching begin(). If no transaction is open, signal an error.
  • commit(): Closes the innermost open transaction and folds its writes into the enclosing scope. That scope is the parent transaction if there is one, otherwise the base store. If no transaction is open, signal an error.

Example

db = TransactionalDB()
db.set("a", 10)
db.begin()
db.set("a", 20)
db.commit()
print(db.get("a"))   # 20

db.begin()
db.set("a", 30)
db.rollback()
print(db.get("a"))   # 20

Required interface

class TransactionalDB:
    def __init__(self): ...
    def set(self, key, value): ...
    def get(self, key): ...
    def begin(self): ...
    def rollback(self): ...
    def commit(self): ...

What to discuss

  1. Describe your data structure and why it gives the right visibility rules.
  2. State what get returns for an unknown key and how you report an error from rollback/commit with no open transaction.
  3. Give the time complexity of each operation.
  4. Explain what happens when an inner transaction commits and then its parent rolls back.
  5. Follow-up: how would you make get O(1) regardless of depth, and how would you add a delete(key) operation?

Hints

Hint 1

Think of each open transaction as a scope that only remembers the writes made while it was innermost. What container holds a sequence of scopes where you only touch the most recent one?

Hint 2

A read should check the innermost scope first and move outward until it finds the key. Test membership with `in`, not truthiness, so a stored value of 0 is not mistaken for a missing key.

Hint 3

Rollback just discards the innermost scope. Commit discards it too, but only after copying its entries over the matching entries in the scope beneath it. Never remove the base scope.