In-Memory Transactional Key-Value Store

Easy · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Build an in-memory string key-value engine supporting arbitrarily nested transactions, and expose it via:

def run_transactional_store(operations: List[List[str]]) -> List[object]:

Process operations in order on a single initially empty store and return a list of equal length holding each command's result:

  • ["set", key, value] — Bind key to value in the currently visible state and return None.
  • ["get", key] — Return the currently visible string bound to key, or None if key is not present.
  • ["unset", key] — Remove key from the currently visible state (doing nothing if key is already absent) and return None.
  • ["count", value] — Return the integer number of currently visible keys whose value equals value, reflecting all uncommitted writes that have not been rolled back.
  • ["begin"] — Start a new innermost transaction scope and return None.
  • ["rollback"] — Undo every write performed inside the innermost open transaction scope, close that scope, and return True. If no transaction scope is open, leave the store unchanged and return False.
  • ["commit"] — Close the innermost open transaction scope and return True: if an enclosing parent transaction exists, transfer this scope's writes into that parent (so rolling back the parent later still undoes them); if closing the outermost transaction, make the writes permanent. If no transaction scope is open, return False.

Examples

Example 1

Input:
  operations = [
    ["set", "host", "alpha"],
    ["begin"],
    ["set", "host", "beta"],
    ["set", "replica", "beta"],
    ["count", "beta"],
    ["begin"],
    ["unset", "host"],
    ["count", "beta"],
    ["rollback"],
    ["get", "host"],
    ["commit"],
    ["count", "beta"]
  ]
Output:
  [None, None, None, None, 2, None, None, 1, True, "beta", True, 2]

Walk-through: Inside the outer transaction, "host" is overwritten with "beta" and "replica" is set to "beta", giving count("beta") == 2. An inner transaction deletes "host", dropping count("beta") to 1, then rolls back so "host" returns to "beta". Committing the outer transaction makes both "beta" entries permanent.

Example 2

Input:
  operations = [
    ["set", "mode", "safe"],
    ["begin"],
    ["begin"],
    ["set", "mode", "fast"],
    ["commit"],
    ["get", "mode"],
    ["rollback"],
    ["get", "mode"],
    ["rollback"]
  ]
Output:
  [None, None, None, None, True, "fast", True, "safe", False]

Walk-through: Committing the inner transaction merges "mode" = "fast" into the outer transaction rather than making it permanent. Rolling back the outer transaction therefore restores "mode" to "safe", and the final ["rollback"] returns False because no transaction remains open.

Constraints

  • 0 <= len(operations) <= 200,000
  • Every key and value is a non-empty string.
  • Simultaneously open nested transactions can reach depth 100,000.
  • Operations must run in O(1) expected amortized time; cloning the full key-value map on begin or linearly scanning keys on count will time out.

Step-by-step walkthrough

  1. Understand the operations and transaction rules

    We simulate an in-memory string key-value store across a list of operations and return one output item per operation:

    Operation Effect on visible state Return value
    ["set", k, v] Store k -> v None
    ["get", k] Read current visible value of k Value string, or None if absent
    ["unset", k] Remove k if present (no-op if absent) None
    ["count", v] Count how many visible keys currently equal v Integer count
    ["begin"] Open a new innermost transaction None
    ["rollback"] Undo all changes made since the innermost begin True, or False if none is open
    ["commit"] Merge the innermost transaction into its parent (or make permanent if outermost) True, or False if none is open

    Two rules matter most:

    1. Reads see uncommitted work: get and count always reflect every open transaction that has not been rolled back.
    2. Inner commits are not yet permanent: committing a child transaction folds its changes into its parent, so rolling back the parent later must still undo the child's changes.
  2. Why copying the dictionary on `begin` fails

    The most direct brute-force design pushes dict(data) onto a stack at every begin, pops and restores that snapshot on rollback, throws the snapshot away on commit, and scans data.values() for every count.

    That logic is easy to verify, so it makes a great test oracle, but it breaks the constraints:

    • Up to 200,000 operations and nesting depth up to 100,000 mean 50,000 keys followed by 50,000 begin calls would copy 2.5 * 10^9 dictionary entries.
    • 50,000 count calls over 50,000 keys would scan another 2.5 * 10^9 entries.

    To hit O(1) expected time per operation, we must avoid copying the store on begin and avoid scanning keys on count.

  3. Key idea: one live store, one shared undo log, and bookmark indices

    Instead of saving snapshots of the whole store, keep one live dictionary data that always holds the current visible state. That makes get(key) a single dictionary lookup regardless of transaction depth.

    Whenever a write happens inside an open transaction, we record how to reverse that single write by appending (key, old_value) to a shared list undo_log. Because real values in this problem are nonempty strings, old_value = None unambiguously serves as a sentinel meaning "this key did not exist before the write."

    To track nested transactions without creating separate dictionaries per level, we keep a stack frame_starts storing the length of undo_log when each open transaction began:

    Start: data = {"host": "alpha"}
    
    1) begin                   -> frame_starts = [0],     undo_log = []
    2) set "host" = "beta"     -> frame_starts = [0],     undo_log = [("host", "alpha")]
    3) begin                   -> frame_starts = [0, 1],  undo_log = [("host", "alpha")]
    4) set "replica" = "beta"  -> frame_starts = [0, 1],  undo_log = [("host", "alpha"), ("replica", None)]
                                                                      ^depth 1           ^depth 2
    
    If we COMMIT depth 2:
       pop 1 from frame_starts -> frame_starts = [0]
       undo_log is untouched: [("host", "alpha"), ("replica", None)] now belongs to depth 1!
    
    If depth 1 later ROLLS BACK:
       pop 0 from frame_starts -> pop ("replica", None), then pop ("host", "alpha")
       both depth 2 and depth 1 writes are undone!
    

    Every undo entry is appended once and popped or cleared once, so even 100,000 nested begin and commit calls take O(1) time each.

  4. Keep `value_counts` synchronized through one write helper

    To answer count(value) in O(1) time, we maintain a dictionary value_counts mapping each value to how many visible keys currently hold it.

    Whenever a key changes from old_value to new_value: - If old_value was present, decrement value_counts[old_value] (and delete the key from value_counts if it reaches 0 so unused values do not linger in memory). - If new_value is not None, store data[key] = new_value and increment value_counts[new_value].

    By placing this logic in one helper _apply_write and routing all mutations through it (set, unset, and rollback), value_counts can never drift out of sync with data. For user writes (_record_and_write), we also check if old_value == new_value: return first so no-op calls (unset on a missing key, or set to the exact same value) do not add useless undo entries.

    from typing import Dict, List, Optional, Tuple
    
    
    class TransactionalStore:
        def __init__(self) -> None:
            # data: live visible store mapping key -> current value, e.g. {"a": "y"}.
            self.data: Dict[str, str] = {}
            # value_counts: frequency map of value -> visible key count, e.g. {"y": 2}.
            self.value_counts: Dict[str, int] = {}
            # undo_log: stack of (key, previous_value) tuples recorded inside open transactions.
            # A previous_value of None is a sentinel meaning the key did not exist before the write.
            self.undo_log: List[Tuple[str, Optional[str]]] = []
            # frame_starts: stack of undo_log lengths; frame_starts[d] marks where depth d+1 began.
            self.frame_starts: List[int] = []
    
        def _apply_write(self, key: str, new_value: Optional[str]) -> None:
            """Mutate visible state (None deletes key) and keep value_counts in sync."""
            old_value = self.data.get(key)
    
            # Phase 1: remove the key's contribution to its previous value's count.
            if old_value is not None:
                self.value_counts[old_value] -= 1
                if self.value_counts[old_value] == 0:
                    del self.value_counts[old_value]
    
            # Phase 2: delete the key or store new_value and increment its count.
            if new_value is None:
                self.data.pop(key, None)
            else:
                self.data[key] = new_value
                self.value_counts[new_value] = self.value_counts.get(new_value, 0) + 1
    
        def _record_and_write(self, key: str, new_value: Optional[str]) -> None:
            """Apply a user write, logging the prior state first if a transaction is open."""
            old_value = self.data.get(key)
            # Skip no-ops (unsetting an absent key, or setting a key to its current value)
            # so we do not pollute undo_log or churn value_counts.
            if old_value == new_value:
                return
            if self.frame_starts:
                self.undo_log.append((key, old_value))
            self._apply_write(key, new_value)
    
  5. Implement store operations and transaction boundaries

    Two subtle details are critical in rollback and commit:

    1. Undo newest-first in rollback: Suppose "k" starts at "v0", and inside one transaction we set "k" to "v1" and then "v2". The log records ("k", "v0") followed by ("k", "v1"). Popping from the back restores "v1" first and "v0" last, landing on the exact pre-transaction value "v0".
    2. Call _apply_write, not _record_and_write, during rollback: If an outer transaction is still open, calling _record_and_write while undoing would append a fresh undo record for every record we pop, causing an infinite loop!
    3. Clear undo_log on the outermost commit: Once frame_starts becomes empty, no open transaction remains, so the logged history can never be rolled back and we free it immediately.
        def set(self, key: str, value: str) -> None:
            self._record_and_write(key, value)
    
        def get(self, key: str) -> Optional[str]:
            return self.data.get(key)
    
        def unset(self, key: str) -> None:
            self._record_and_write(key, None)
    
        def count(self, value: str) -> int:
            return self.value_counts.get(value, 0)
    
        def begin(self) -> None:
            # Bookmark the current end of undo_log so rollback knows where to stop.
            self.frame_starts.append(len(self.undo_log))
    
        def rollback(self) -> bool:
            if not self.frame_starts:
                return False
            stop_index = self.frame_starts.pop()
            # Replay undo entries from newest to oldest so a key modified multiple times
            # in this transaction ends at the value it had right before begin().
            while len(self.undo_log) > stop_index:
                key, previous_value = self.undo_log.pop()
                # Call _apply_write directly so undoing does not append new undo records.
                self._apply_write(key, previous_value)
            return True
    
        def commit(self) -> bool:
            if not self.frame_starts:
                return False
            # Dropping the innermost bookmark hands this transaction's undo entries
            # to its parent in O(1) time without copying any dictionary entries.
            self.frame_starts.pop()
            if not self.frame_starts:
                # Outermost commit: changes are now permanent and cannot be rolled back.
                self.undo_log.clear()
            return True
    
  6. Trace Example 1 step by step

    Let's trace every state transition on Example 1:

    Operation                   undo_log                                               frame_starts  data                                  value_counts   Return
    ------------------------------------------------------------------------------------------------------------------------------------------------------------
    ["set","host","alpha"]      []                                                     []            {"host":"alpha"}                      {"alpha": 1}   None
    ["begin"]                   []                                                     [0]           {"host":"alpha"}                      {"alpha": 1}   None
    ["set","host","beta"]       [("host","alpha")]                                     [0]           {"host":"beta"}                       {"beta": 1}    None
    ["set","replica","beta"]    [("host","alpha"), ("replica",None)]                   [0]           {"host":"beta","replica":"beta"}      {"beta": 2}    None
    ["count","beta"]            [("host","alpha"), ("replica",None)]                   [0]           {"host":"beta","replica":"beta"}      {"beta": 2}    2
    ["begin"]                   [("host","alpha"), ("replica",None)]                   [0, 2]        {"host":"beta","replica":"beta"}      {"beta": 2}    None
    ["unset","host"]            [("host","alpha"), ("replica",None), ("host","beta")]  [0, 2]        {"replica":"beta"}                    {"beta": 1}    None
    ["count","beta"]            [("host","alpha"), ("replica",None), ("host","beta")]  [0, 2]        {"replica":"beta"}                    {"beta": 1}    1
    ["rollback"]                [("host","alpha"), ("replica",None)]                   [0]           {"host":"beta","replica":"beta"}      {"beta": 2}    True
    ["get","host"]              [("host","alpha"), ("replica",None)]                   [0]           {"host":"beta","replica":"beta"}      {"beta": 2}    "beta"
    ["commit"]                  []                                                     []            {"host":"beta","replica":"beta"}      {"beta": 2}    True
    ["count","beta"]            []                                                     []            {"host":"beta","replica":"beta"}      {"beta": 2}    2
    

    At ["rollback"], stop_index = 2, so only ("host", "beta") is popped and restored, leaving the outer transaction's two undo entries intact. At ["commit"], frame_starts becomes empty, so undo_log is cleared and both "beta" bindings become permanent.

  7. Complete solution

    Finally, run_transactional_store creates a TransactionalStore, dispatches each operation by name, and collects the return values in order.

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TransactionalStore:
        def __init__(self) -> None:
            # data: live visible store mapping key -> current value, e.g. {"a": "y"}.
            self.data: Dict[str, str] = {}
            # value_counts: frequency map of value -> visible key count, e.g. {"y": 2}.
            self.value_counts: Dict[str, int] = {}
            # undo_log: stack of (key, previous_value) tuples recorded inside open transactions.
            # A previous_value of None is a sentinel meaning the key did not exist before the write.
            self.undo_log: List[Tuple[str, Optional[str]]] = []
            # frame_starts: stack of undo_log lengths; frame_starts[d] marks where depth d+1 began.
            self.frame_starts: List[int] = []
    
        def _apply_write(self, key: str, new_value: Optional[str]) -> None:
            """Mutate visible state (None deletes key) and keep value_counts in sync."""
            old_value = self.data.get(key)
    
            # Phase 1: remove the key's contribution to its previous value's count.
            if old_value is not None:
                self.value_counts[old_value] -= 1
                if self.value_counts[old_value] == 0:
                    del self.value_counts[old_value]
    
            # Phase 2: delete the key or store new_value and increment its count.
            if new_value is None:
                self.data.pop(key, None)
            else:
                self.data[key] = new_value
                self.value_counts[new_value] = self.value_counts.get(new_value, 0) + 1
    
        def _record_and_write(self, key: str, new_value: Optional[str]) -> None:
            """Apply a user write, logging the prior state first if a transaction is open."""
            old_value = self.data.get(key)
            # Skip no-ops (unsetting an absent key, or setting a key to its current value)
            # so we do not pollute undo_log or churn value_counts.
            if old_value == new_value:
                return
            if self.frame_starts:
                self.undo_log.append((key, old_value))
            self._apply_write(key, new_value)
    
        def set(self, key: str, value: str) -> None:
            self._record_and_write(key, value)
    
        def get(self, key: str) -> Optional[str]:
            return self.data.get(key)
    
        def unset(self, key: str) -> None:
            self._record_and_write(key, None)
    
        def count(self, value: str) -> int:
            return self.value_counts.get(value, 0)
    
        def begin(self) -> None:
            # Bookmark the current end of undo_log so rollback knows where to stop.
            self.frame_starts.append(len(self.undo_log))
    
        def rollback(self) -> bool:
            if not self.frame_starts:
                return False
            stop_index = self.frame_starts.pop()
            # Replay undo entries from newest to oldest so a key modified multiple times
            # in this transaction ends at the value it had right before begin().
            while len(self.undo_log) > stop_index:
                key, previous_value = self.undo_log.pop()
                # Call _apply_write directly so undoing does not append new undo records.
                self._apply_write(key, previous_value)
            return True
    
        def commit(self) -> bool:
            if not self.frame_starts:
                return False
            # Dropping the innermost bookmark hands this transaction's undo entries
            # to its parent in O(1) time without copying any dictionary entries.
            self.frame_starts.pop()
            if not self.frame_starts:
                # Outermost commit: changes are now permanent and cannot be rolled back.
                self.undo_log.clear()
            return True
    
    
    def run_transactional_store(operations: List[List[str]]) -> List[object]:
        store = TransactionalStore()
        results: List[object] = []
    
        # Dispatch each command and record one return value per operation.
        for op in operations:
            op_type = op[0]
            if op_type == "set":
                store.set(op[1], op[2])
                results.append(None)
            elif op_type == "get":
                results.append(store.get(op[1]))
            elif op_type == "unset":
                store.unset(op[1])
                results.append(None)
            elif op_type == "count":
                results.append(store.count(op[1]))
            elif op_type == "begin":
                store.begin()
                results.append(None)
            elif op_type == "rollback":
                results.append(store.rollback())
            elif op_type == "commit":
                results.append(store.commit())
            else:
                raise ValueError(f"unknown operation: {op_type}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine editing a whiteboard while keeping a single undo log (an append-only list that records what a key's old value was right before you changed it) and placing a numbered bookmark on that list every time you start a nested transaction (begin). Because the whiteboard itself (data) always shows the latest state— alongside a live tally sheet (value_counts) of how many keys hold each value—get and count are instant single-dictionary lookups at any nesting depth.

The naive approach copies the entire dictionary at every begin and scans all keys for every count. With 50,000 keys and 50,000 nested begin or count calls, copying and scanning perform billions of steps and time out. Even keeping one small undo dictionary per transaction fails if an inner commit naively copies its entries into its parent at every level across 50,000 nested commits.

With one shared undo_log and a stack of bookmark positions frame_starts, begin and inner commit touch only a single integer bookmark (tracing Example 2):

1. set("mode", "safe")  -> data={"mode": "safe"}, undo_log=[], frame_starts=[]
2. begin() (outer)      -> bookmark index 0: frame_starts=[0]
3. begin() (inner)      -> bookmark index 0: frame_starts=[0, 0]
4. set("mode", "fast")  -> log old value: undo_log=[("mode", "safe")], data={"mode": "fast"}
5. commit() (inner)     -> pop inner bookmark: frame_starts=[0]; undo_log stays intact!
6. rollback() (outer)   -> pop bookmark 0, pop ("mode", "safe") -> data={"mode": "safe"} again!
7. rollback() (none)    -> frame_starts is empty -> returns False.

Complexity

Let n be the total number of operations.

  • Time: Amortized O(1) expected time per operation, and O(n) expected time overall (amortized O(1) means an occasional operation like rollback may do multiple steps, but averaged across the whole sequence each operation pays only a constant cost). get, count, set, unset, begin, and nested commit each perform a constant number of dictionary lookups/updates (O(1) expected) and list pushes/pops (O(1)). Although rollback and the outermost commit process multiple undo entries, every entry in undo_log is appended at most once by a write and removed at most once by a rollback or final clear(), so total log work across the entire run never exceeds n.
  • Space: O(n) worst-case auxiliary space. data and value_counts store at most one entry per active key or value, undo_log stores at most one tuple per write inside open transactions, and frame_starts stores at most one integer per open begin.

Edge cases

  • rollback or commit when no transaction is open: frame_starts is empty, so both immediately return False without modifying data or value_counts.
  • unset of a missing key (or set to the identical value): old_value == new_value triggers an early return, so nothing changes and no redundant record is pushed to undo_log.
  • Distinguishing an absent key from a present key: None acts as a sentinel value (a special marker distinct from all valid data values) meaning "key was absent," which is safe because keys and values are guaranteed to be nonempty strings. Rolling back the creation of a brand-new key sees previous_value = None and deletes the key rather than storing None.
  • Multiple writes to the same key inside one transaction: Each real change logs a tuple, and rollback pops from newest to oldest, so the earliest pre-transaction value is applied last and wins.
  • Inner commit followed by outer rollback: Inner commit only pops its bookmark from frame_starts, leaving its undo tuples above the parent's bookmark so the parent's rollback undoes both.
  • Extreme nesting (100,000 levels): Each begin appends a single integer to frame_starts, using minimal memory and O(1) time.

Common mistakes

  • Copying data on every begin: Easy to write, but costs O(keys) per begin and times out on deep transaction chains.
  • Making an inner commit permanent immediately: Clearing undo_log on every commit prevents an enclosing parent transaction from rolling back the child's writes.
  • Replaying undo entries oldest-first instead of newest-first: If "k" changed "v0" -> "v1" -> "v2", applying ("k", "v0") before ("k", "v1") leaves "k" stuck at "v1" instead of "v0".
  • Updating value_counts in set/unset but forgetting rollback: Any separate rollback code path risks count drift; routing every state change through _apply_write makes drift impossible.
  • Calling _record_and_write inside rollback: When an outer transaction is still open, logging during an undo appends one new record for every record popped and loops forever.
  • Naively copying per-frame undo maps on commit: Copying a child dictionary of 50,000 keys up through 50,000 parent commits takes 2.5 * 10^9 steps.

Alternative approaches

  • Per-transaction map of first-seen old values with small-to-large merging: Each frame stores a dict mapping key -> original_value_before_this_frame, recording only the first write to each key in that frame. On inner commit, entries merge into the parent without overwriting keys the parent already recorded. To avoid O(n^2) repeated copies, always merge the smaller dict into the larger dict (swapping when the child is larger), giving O(n log n) total time and bounding memory by unique (frame, key) pairs even if one key is overwritten millions of times.
  • Stacked overlay maps with tombstones: Each begin pushes an empty write-buffer dict, and deletes store a tombstone marker. begin and rollback are O(1), but get may have to walk all 100,000 layers unless combined with extra index bookkeeping, and commit still has to merge layers.

Follow-up questions

  • How would you redesign the store to support concurrent readers and writers via snapshot isolation (MVCC)? Mutating data in place with an undo log only works for a single thread at a time. Under multi-version concurrency control (MVCC)—a concurrency scheme where writes append new timestamped versions of a value instead of overwriting it in place—each transaction gets a start_ts, reads the latest version committed at or before start_ts, and stages its own writes privately. On commit, it checks whether another transaction committed a conflicting write after start_ts and, if not, publishes its buffered writes under a new commit timestamp; fast count(value) then requires maintaining versioned count deltas or per-snapshot summaries.
  • If each transaction kept its own per-key undo map instead of a shared log, how would you merge an inner commit into its parent efficiently without losing earlier values? With our flat undo_log, no merge loop is needed at all: dropping the child's frame_starts bookmark leaves the child's newer undo tuples after the parent's older undo tuples, so a later parent rollback pops newest-first and finishes on the parent's original state. If instead each transaction stores a first_old_value dictionary, the rule on commit is "keep the parent's entry whenever a key exists in both," and swap-plus-insert when the child map is bigger so each entry moves at most log2(n) times.
  • How would you add durability so committed state survives a process crash? Use a write-ahead log (WAL)—an append-only disk file where committed changes are flushed before acknowledging success—that records only committed mutations. Uncommitted inner transactions stay purely in RAM; standalone writes outside any transaction and the net key changes of an outermost commit are written as checksummed log records and fsynced before returning True. After a crash, recovery loads the latest periodic snapshot of data, replays valid WAL records after that snapshot, ignores any half-written trailing record whose checksum fails, and rebuilds value_counts in one pass.

Follow-up questions

Similar questions

More Lyft interview questions

All 52 Lyft questions →