← Questions
Key-value store with nested transaction rollback
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Implement an in-memory key-value store whose string keys map to string values. It supports transactions, and transactions can be nested.
Implement the class KeyValueStore:
-
KeyValueStore()creates an empty store. -
set(key: str, value: str) -> Nonestoresvalueunderkeyand overwrites any existing value. -
get(key: str) -> str | Nonereturns the current value forkey, orNoneif the key is absent. -
unset(key: str) -> Noneremoveskey. Removing a key that does not exist does nothing. -
begin() -> Noneopens a new transaction. If a transaction is already open, the new one is nested inside it. -
rollback() -> booldiscards every change made in the innermost open transaction and closes it. ReturnsFalseif no transaction is open. -
commit() -> boolcloses the innermost open transaction and keeps its changes. If it is nested, its changes become part of the enclosing transaction, so a later rollback of the parent still undoes them. Only committing the outermost transaction makes changes permanent. ReturnsFalseif no transaction is open.
Reads always see the latest changes, including uncommitted ones in open transactions.
Constraints
- Up to 10^5 operations; transactions can nest up to 10^4 deep.
-
get,setandunsetshould run in O(1) average time. -
beginshould be O(1).commitandrollbackshould cost time proportional to the number of keys the innermost transaction changed, not the size of the store.
Example 1
kv.set("color", "red")
kv.begin()
kv.set("color", "blue")
kv.set("size", "L")
kv.get("color") -> "blue"
kv.rollback() -> True
kv.get("color") -> "red"
kv.get("size") -> None
kv.rollback() -> False
Example 2 (nested)
kv.set("n", "0")
kv.begin()
kv.set("n", "1")
kv.begin()
kv.unset("n")
kv.commit() -> True # folds into the outer transaction
kv.get("n") -> None
kv.rollback() -> True # undoes both levels
kv.get("n") -> "0"
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding


