In-Memory Key-Value Store with Nested Transactions

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory string-to-string dictionary class KVStore and a line-oriented command runner run_commands(lines) supporting transaction scopes that can nest to any depth.

Programmatic API (KVStore)

class KVStore:
    def __init__(self) -> None: ...
    def set(self, key: str, value: str) -> None: ...
    def get(self, key: str) -> Optional[str]: ...
    def begin(self) -> None: ...
    def rollback(self) -> bool: ...
    def commit(self) -> bool: ...
  • set(key, value): Bind key to value inside the currently active scope (or directly in the base dictionary when no scope is open), replacing any prior binding for key.
  • get(key): Return the latest string currently visible for key, or None when key has no active binding.
  • begin(): Open a new inner transaction scope on top of any already-open scopes.
  • rollback(): Discard every write performed inside the innermost open scope, close only that scope, and return True. If zero scopes are open, leave all bindings untouched and return False.
  • commit(): Make every write across all open scopes permanent at once, close every open scope, and return True. If zero scopes are open, return False.

Text Command Runner (run_commands)

def run_commands(lines: List[str]) -> List[str]: ...

Execute lines sequentially against a brand-new KVStore and return all emitted output strings in order:

  • "SET <key> <value>" calls store.set(key, value) and emits nothing.
  • "GET <key>" emits the string returned by store.get(key), or "NULL" when store.get(key) is None.
  • "BEGIN" calls store.begin() and emits nothing.
  • "ROLLBACK" calls store.rollback(), emitting "NO TRANSACTION" only when it returns False.
  • "COMMIT" calls store.commit(), emitting "NO TRANSACTION" only when it returns False.
  • Raise ValueError if any line is blank, uses an unrecognized command name, or passes the wrong number of whitespace-separated tokens.

Transactional Semantics

  • Repeated updates in one scope: Overwriting the same key multiple times inside one scope must still revert all the way back to the state before that scope's BEGIN if rolled back.
  • Newly inserted keys: If a key did not exist prior to a scope's BEGIN and is written inside that scope, rolling back that scope removes the key completely (get returns None).
  • Nested shadowing: Writes in a deeper scope temporarily hide bindings from enclosing scopes; rolling back the deeper scope reveals the enclosing scope's binding again.

Examples

Example 1

lines = [
    "SET host alpha",
    "BEGIN",
    "SET host beta",
    "BEGIN",
    "SET host gamma",
    "SET host delta",
    "SET port 8080",
    "GET host",
    "GET port",
    "ROLLBACK",
    "GET host",
    "GET port",
    "COMMIT",
    "ROLLBACK",
    "GET host",
]
output = ["delta", "8080", "beta", "NULL", "NO TRANSACTION", "beta"]

Walk-through: 1. Outside any transaction, host starts at "alpha". The outer BEGIN updates host to "beta". 2. Inside the nested BEGIN, host is written twice ("gamma" then "delta") and port is created as "8080", so the two GET calls emit "delta" and "8080". 3. The first ROLLBACK closes only the inner scope: host reverts past both inner writes back to "beta", and port disappears ("NULL"). 4. COMMIT finalizes all remaining open scopes, so the subsequent ROLLBACK has nothing to undo ("NO TRANSACTION") and host stays "beta".

Example 2

lines = [
    "GET mode",
    "COMMIT",
    "BEGIN",
    "SET mode debug",
    "GET mode",
    "ROLLBACK",
    "GET mode",
    "ROLLBACK",
]
output = ["NULL", "NO TRANSACTION", "debug", "NULL", "NO TRANSACTION"]

Walk-through: mode is initially absent ("NULL"), and COMMIT before any BEGIN emits "NO TRANSACTION". Opening a scope and setting mode makes GET mode emit "debug", rolling back deletes mode again ("NULL"), and a second ROLLBACK emits "NO TRANSACTION".

Constraints

  • Keys and values are non-empty strings containing no whitespace characters.
  • Transaction nesting depth can exceed 1,000 levels, so implementations must not rely on call-stack recursion per BEGIN.
  • get, set, and begin should run in O(1) average time, commit in O(1) amortized time, and rollback in O(k) average time where k is the number of distinct keys modified in the innermost scope (avoid copying the entire store on begin).

Step-by-step walkthrough

  1. Understand the commands and nested transaction rules

    We need an in-memory dictionary mapping string keys to string values with transaction scopes that can nest to any depth through five operations:

    • SET key value: bind key to value in the currently active scope.
    • GET key: emit the latest visible value of key, or NULL when key is not bound.
    • BEGIN: push a new inner transaction scope (possibly inside an already-open scope).
    • ROLLBACK: undo every write performed inside the innermost open scope and close only that scope.
    • COMMIT: make all writes across every open scope permanent at once and close all open scopes.

    Let's pin down the exact boundary rules up front:

    • Executing ROLLBACK or COMMIT when zero scopes are open emits NO TRANSACTION and leaves stored bindings unchanged.
    • Every GET sees the newest binding in effect — whether written in the innermost scope, an enclosing scope, or outside any transaction.
    • Separating KVStore (clean Python methods returning Optional[str] and bool) from run_commands(lines) (whitespace parser and text formatter) keeps the data structure modular and easy to test directly.
  2. Why full snapshots are too slow on large stores

    The simplest mental model keeps a stack of full dictionary copies: - BEGIN pushes dict(self.data) onto a snapshot list. - ROLLBACK pops the last snapshot and replaces self.data with it. - COMMIT clears the snapshot list.

    Naive snapshot stack with 1,000,000 keys in self.data:
      BEGIN #1  -> copies 1,000,000 entries
      BEGIN #2  -> copies 1,000,000 entries
      ...
      BEGIN #10 -> copies 1,000,000 entries  (10,000,000 copied entries just to edit 1 key!)
    

    That snapshot model makes a great reference oracle in unit tests because its semantics are trivially right. As a real implementation, however, BEGIN costs O(n) time and O(n) memory for n stored keys — even when a scope modifies just one key! Transaction work should scale only with the keys actually modified, never with the total size of the dictionary.

  3. Core idea: write-through dictionary plus a stack of undo logs

    Instead of cloning entries that never change, record only the prior value of keys that do get touched:

    1. Maintain one primary dictionary self.data that always stores the currently visible bindings (write-through). Because self.data is always current, GET is a single O(1) lookup regardless of nesting depth!
    2. Maintain a stack self.undo_logs of dictionaries — one dictionary per open scope, with the innermost scope at self.undo_logs[-1]. Each undo log maps key -> binding that key held right before this scope FIRST touched it.
    State during Example 1 after:
      SET host alpha -> BEGIN -> SET host beta -> BEGIN -> SET host gamma -> SET port 8080
    
      self.data (always shows currently visible bindings):
        {"host": "gamma", "port": "8080"}
    
      self.undo_logs (stack from outermost to innermost):
        [ {"host": "alpha"},                   <-- outer BEGIN's undo log
          {"host": "beta", "port": ABSENT} ]   <-- inner BEGIN's undo log (top of stack)
    

    Look at the four behaviors this gives us automatically:

    • Repeated updates in one scope: Inside the inner scope of Example 1, SET host gamma sees "host" not in current_log and records "host": "beta". The next command SET host delta sees "host" already in current_log and leaves "beta" untouched, so ROLLBACK restores "beta" directly rather than "gamma".
    • Newly inserted keys: Because port did not exist before the inner BEGIN, we save a private sentinel _ABSENT = object() in current_log["port"]. On ROLLBACK, seeing _ABSENT tells us to del self.data["port"] so GET port returns None ("NULL").
    • Nested shadowing: The inner scope logs the outer scope's binding ("beta"), so rolling back the inner scope restores "beta", while rolling back the outer scope later would restore "alpha".
    • Instant COMMIT: Every SET already updated self.data! Finalizing all open scopes simply resets self.undo_logs = [] so none of those updates can ever be undone.
  4. Implement KVStore: SET and GET

    Let's write __init__, set, and get. Notice the guard if key not in current_log: inside set — skipping the log write on later assignments to the same key in the same scope preserves the pre-BEGIN binding.

    from typing import Dict, List, Optional
    
    # Unique sentinel marking "this key did not exist before this transaction touched it".
    # Using a private object avoids ambiguity if None were ever allowed as a stored value.
    _ABSENT = object()
    
    
    class KVStore:
        """In-memory key-value store supporting arbitrarily nested transactions."""
    
        def __init__(self) -> None:
            # self.data: main dictionary mapping key -> currently visible value, e.g. {"a": "20"}.
            # Every SET writes straight into self.data ("write-through") so GET is always O(1).
            self.data: Dict[str, str] = {}
    
            # self.undo_logs: stack of dicts, one per open transaction (innermost at index -1).
            # Each dict maps key -> value before that transaction FIRST modified key (or _ABSENT),
            # e.g. [{"a": "10"}, {"a": "20", "b": _ABSENT}].
            self.undo_logs: List[dict] = []
    
        def set(self, key: str, value: str) -> None:
            # Phase 1: if a transaction is open, save the pre-transaction value in the innermost log.
            if self.undo_logs:
                current_log = self.undo_logs[-1]
                # Record ONLY the first write to `key` in this transaction; later writes in the
                # same scope must not overwrite the original pre-BEGIN value we need for rollback.
                if key not in current_log:
                    current_log[key] = self.data.get(key, _ABSENT)
    
            # Phase 2: write the new value directly into the main dictionary.
            self.data[key] = value
    
        def get(self, key: str) -> Optional[str]:
            # Because writes go straight to self.data, reads never need to scan transaction scopes.
            return self.data.get(key)
    
  5. Implement BEGIN, ROLLBACK, and COMMIT

    Now let's write the three scope-management methods:

    • begin() appends an empty dictionary {} onto self.undo_logs in O(1) time.
    • rollback() returns False when self.undo_logs is empty. Otherwise it pops current_log from the top of the stack and restores every logged key in self.data — deleting keys marked _ABSENT and writing back old strings for everything else.
    • commit() returns False when self.undo_logs is empty, and otherwise clears self.undo_logs = [].
        def begin(self) -> None:
            # Push a fresh empty undo log for the newly opened innermost transaction.
            self.undo_logs.append({})
    
        def rollback(self) -> bool:
            if not self.undo_logs:
                return False
    
            # Pop only the innermost transaction's undo log and restore every key it touched.
            current_log = self.undo_logs.pop()
            for key, old_value in current_log.items():
                if old_value is _ABSENT:
                    # Key was created inside this transaction, so remove it completely.
                    del self.data[key]
                else:
                    self.data[key] = old_value
            return True
    
        def commit(self) -> bool:
            if not self.undo_logs:
                return False
    
            # All latest values already live in self.data; dropping every undo log makes
            # all open transactions permanent at once.
            self.undo_logs = []
            return True
    
  6. Parse text commands in run_commands

    run_commands wraps KVStore with a strict line-by-line parser: - Split each line on whitespace and verify both the verb and exact argument count. - Convert None from store.get(key) into "NULL", and False from rollback() / commit() into "NO TRANSACTION". - Raise ValueError on blank lines, unknown verbs, or wrong argument counts.

    def run_commands(lines: List[str]) -> List[str]:
        store = KVStore()
        printed_lines: List[str] = []
    
        for line in lines:
            parts = line.split()
            if not parts:
                raise ValueError("empty command")
    
            command = parts[0]
            args = parts[1:]
    
            if command == "SET" and len(args) == 2:
                key, value = args[0], args[1]
                store.set(key, value)
            elif command == "GET" and len(args) == 1:
                value = store.get(args[0])
                if value is None:
                    printed_lines.append("NULL")
                else:
                    printed_lines.append(value)
            elif command == "BEGIN" and not args:
                store.begin()
            elif command == "ROLLBACK" and not args:
                if not store.rollback():
                    printed_lines.append("NO TRANSACTION")
            elif command == "COMMIT" and not args:
                if not store.commit():
                    printed_lines.append("NO TRANSACTION")
            else:
                raise ValueError("bad command: " + line)
    
        return printed_lines
    
  7. Walk through Example 1 and compare iterative vs recursive designs

    Let's trace Example 1 end to end (A stands for _ABSENT):

    Command          Emitted          self.data                          self.undo_logs
    -----------------------------------------------------------------------------------------------------------
    SET host alpha   -                {host: "alpha"}                    []
    BEGIN            -                {host: "alpha"}                    [{}]
    SET host beta    -                {host: "beta"}                     [{host: "alpha"}]
    BEGIN            -                {host: "beta"}                     [{host: "alpha"}, {}]
    SET host gamma   -                {host: "gamma"}                    [{host: "alpha"}, {host: "beta"}]
    SET host delta   -                {host: "delta"}                    [{host: "alpha"}, {host: "beta"}] (kept!)
    SET port 8080    -                {host: "delta", port: "8080"}      [{host: "alpha"}, {host: "beta", port: A}]
    GET host         delta            {host: "delta", port: "8080"}      [{host: "alpha"}, {host: "beta", port: A}]
    GET port         8080             {host: "delta", port: "8080"}      [{host: "alpha"}, {host: "beta", port: A}]
    ROLLBACK         -                {host: "beta"}                     [{host: "alpha"}]   (port deleted)
    GET host         beta             {host: "beta"}                     [{host: "alpha"}]
    GET port         NULL             {host: "beta"}                     [{host: "alpha"}]
    COMMIT           -                {host: "beta"}                     []                  (all scopes closed)
    ROLLBACK         NO TRANSACTION   {host: "beta"}                     []
    GET host         beta             {host: "beta"}                     []
    

    Why an explicit heap-allocated undo stack beats recursion: - Recursive command loop (calling a helper function recursively on each BEGIN and returning on ROLLBACK / COMMIT): ties transaction depth to Python's ~1,000-frame call stack (RecursionError on deep nesting) and requires awkward multi-frame unwinding when COMMIT closes every open scope at once. - Recursive parent-pointer maps (each BEGIN allocates a child map pointing to its parent, and GET walks parent links recursively on misses): slows GET down to O(d) at depth d, still hits RecursionError on deep chains if recursive, and requires O(total writes) merging work during COMMIT. - Iterative self.undo_logs list (our design): lives on the heap (handling thousands of nested BEGIN calls effortlessly), keeps GET, SET, and BEGIN at O(1), and makes COMMIT instantaneous.

  8. Complete solution

    from typing import Dict, List, Optional
    
    # Unique sentinel marking "this key did not exist before this transaction touched it".
    # Using a private object avoids ambiguity if None were ever allowed as a stored value.
    _ABSENT = object()
    
    
    class KVStore:
        """In-memory key-value store supporting arbitrarily nested transactions."""
    
        def __init__(self) -> None:
            # self.data: main dictionary mapping key -> currently visible value, e.g. {"a": "20"}.
            # Every SET writes straight into self.data ("write-through") so GET is always O(1).
            self.data: Dict[str, str] = {}
    
            # self.undo_logs: stack of dicts, one per open transaction (innermost at index -1).
            # Each dict maps key -> value before that transaction FIRST modified key (or _ABSENT),
            # e.g. [{"a": "10"}, {"a": "20", "b": _ABSENT}].
            self.undo_logs: List[dict] = []
    
        def set(self, key: str, value: str) -> None:
            # Phase 1: if a transaction is open, save the pre-transaction value in the innermost log.
            if self.undo_logs:
                current_log = self.undo_logs[-1]
                # Record ONLY the first write to `key` in this transaction; later writes in the
                # same scope must not overwrite the original pre-BEGIN value we need for rollback.
                if key not in current_log:
                    current_log[key] = self.data.get(key, _ABSENT)
    
            # Phase 2: write the new value directly into the main dictionary.
            self.data[key] = value
    
        def get(self, key: str) -> Optional[str]:
            # Because writes go straight to self.data, reads never need to scan transaction scopes.
            return self.data.get(key)
    
        def begin(self) -> None:
            # Push a fresh empty undo log for the newly opened innermost transaction.
            self.undo_logs.append({})
    
        def rollback(self) -> bool:
            if not self.undo_logs:
                return False
    
            # Pop only the innermost transaction's undo log and restore every key it touched.
            current_log = self.undo_logs.pop()
            for key, old_value in current_log.items():
                if old_value is _ABSENT:
                    # Key was created inside this transaction, so remove it completely.
                    del self.data[key]
                else:
                    self.data[key] = old_value
            return True
    
        def commit(self) -> bool:
            if not self.undo_logs:
                return False
    
            # All latest values already live in self.data; dropping every undo log makes
            # all open transactions permanent at once.
            self.undo_logs = []
            return True
    
    
    def run_commands(lines: List[str]) -> List[str]:
        store = KVStore()
        printed_lines: List[str] = []
    
        for line in lines:
            parts = line.split()
            if not parts:
                raise ValueError("empty command")
    
            command = parts[0]
            args = parts[1:]
    
            if command == "SET" and len(args) == 2:
                key, value = args[0], args[1]
                store.set(key, value)
            elif command == "GET" and len(args) == 1:
                value = store.get(args[0])
                if value is None:
                    printed_lines.append("NULL")
                else:
                    printed_lines.append(value)
            elif command == "BEGIN" and not args:
                store.begin()
            elif command == "ROLLBACK" and not args:
                if not store.rollback():
                    printed_lines.append("NO TRANSACTION")
            elif command == "COMMIT" and not args:
                if not store.commit():
                    printed_lines.append("NO TRANSACTION")
            else:
                raise ValueError("bad command: " + line)
    
        return printed_lines
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of KVStore as a shared whiteboard (self.data) paired with a stack of sticky notes (self.undo_logs), where each BEGIN places a fresh blank sticky note on top of the pile. Whenever you edit a key on the whiteboard (write-through — updating the primary dictionary immediately instead of buffering edits elsewhere), you first glance at the top sticky note: if this note does not list that key yet, you jot down what was on the whiteboard before your edit (an undo log — a minimal record of prior values needed to reverse recent writes). Anyone reading the whiteboard (GET) sees the latest value immediately without flipping through sticky notes. Calling ROLLBACK copies every saved value on the top sticky note back onto the whiteboard and discards that note, while COMMIT throws the entire stack of sticky notes away because the whiteboard already holds all the final values!

Why do the two most common beginner approaches fall short? Cloning the entire dictionary on every BEGIN costs O(n) time and O(n) memory per nested level even when a scope touches only 1 key out of 1,000,000. Conversely, keeping each scope's edits in an isolated per-scope dictionary without updating self.data forces every GET to search backwards through up to d nested scopes in O(d) time (and triggers RecursionError around depth 1,000 if modeled recursively on the call stack).

Let's trace the core of Example 1 to watch how scope shadowing (an inner scope temporarily overriding an outer scope's binding) and repeated writes work together (ABSENT is a sentinel object — a unique marker meaning "this key had no binding before"):

1. SET host alpha  -> data={host:"alpha"},                 undo_logs=[]
2. BEGIN           -> data={host:"alpha"},                 undo_logs=[{}]
3. SET host beta   -> data={host:"beta"},                  undo_logs=[{host:"alpha"}]
4. BEGIN           -> data={host:"beta"},                  undo_logs=[{host:"alpha"}, {}]
5. SET host gamma  -> data={host:"gamma"},                 undo_logs=[{host:"alpha"}, {host:"beta"}]
6. SET host delta  -> data={host:"delta"},                 undo_logs=[{host:"alpha"}, {host:"beta"}] (kept!)
7. SET port 8080   -> data={host:"delta", port:"8080"},    undo_logs=[{host:"alpha"}, {host:"beta", port:ABSENT}]
8. ROLLBACK        -> pops inner log -> data={host:"beta"} (port deleted; outer "beta" restored)
9. COMMIT          -> drops all logs -> data={host:"beta"}, undo_logs=[]

Complexity

Let n be the number of keys currently stored, d be the number of open nested scopes, and k be the number of distinct keys modified inside the innermost open scope. Python dictionary lookups, insertions, and deletions run in O(1) average time.

Operation Time Why
GET O(1) average Reads key directly from self.data in a single hash lookup, independent of nesting depth d.
SET O(1) average Checks key not in self.undo_logs[-1], writes to the top undo log at most once, and updates self.data[key].
BEGIN O(1) Appends one empty {} dictionary onto self.undo_logs.
ROLLBACK O(k) average Pops the innermost undo log and restores or removes each of the k distinct keys touched in that scope.
COMMIT O(1) amortized Drops the self.undo_logs list reference immediately (amortized time means the average cost per operation across a sequence is O(1), since each freed log entry was paid for once by an earlier SET).
  • Space complexity: O(n + L), where n is the number of live keys in self.data and L is the total count of entries stored across all open undo logs (L never exceeds the number of SET calls inside open scopes, and is smaller whenever a key is overwritten repeatedly in the same scope).

Edge cases

  • ROLLBACK or COMMIT when zero scopes are open: self.undo_logs is empty, so the method returns False (run_commands emits "NO TRANSACTION") without touching self.data.
  • GET on an absent key: Returns None ("NULL"), both for keys never written and for keys inserted inside a scope that was later rolled back.
  • Key inserted inside a scope then rolled back: Logged as _ABSENT, so rollback() runs del self.data[key] and leaves zero trace in self.data.
  • Multiple writes to the same key within one scope: SET host gamma followed by SET host delta logs only "beta" before the first write; rolling back restores "beta" rather than "gamma".
  • Writing again in an outer scope after an inner ROLLBACK: If an outer scope creates k = v1 (logging k: _ABSENT), an inner scope sets k = v2 then rolls back to v1, and the outer scope later sets k = v3, k is already recorded in the outer log as _ABSENT, so rolling back the outer scope still deletes k.
  • Deep nesting (d > 1,000): Because self.undo_logs is an explicit heap-allocated Python list rather than call-stack frames, thousands of nested BEGIN calls succeed without RecursionError.

Common mistakes

  • Overwriting the undo-log entry on every SET: Omitting if key not in current_log: causes BEGIN -> SET host gamma -> SET host delta -> ROLLBACK to restore "gamma" instead of the pre-BEGIN value "beta".
  • Setting self.data[key] = None instead of del self.data[key] on rollback: Leaves dead keys inside self.data, breaking len(self.data) or key iteration and colliding with None if arbitrary Python objects are ever stored.
  • Popping only one scope in COMMIT: Here COMMIT finalizes all open scopes (self.undo_logs = []); popping only self.undo_logs[-1] leaves outer scopes open and breaks a subsequent ROLLBACK -> NO TRANSACTION check.
  • Copying dict(self.data) on BEGIN: Degrades BEGIN from O(1) to O(n) time and O(n * d) memory.
  • Modeling nested scopes via function recursion: Hits Python's ~1,000-frame recursion limit and makes multi-frame unwinding on COMMIT brittle.

Alternative approaches

  • Forward-overlay stack (per-scope write buffers): Each BEGIN pushes a dictionary of new writes without touching the base dictionary. ROLLBACK simply pops the top overlay in O(1), at the cost of slowing GET down to an O(d) top-to-bottom scan, slowing COMMIT down to an O(L) merge into the base dictionary, and requiring explicit tombstones (markers saying "deleted in this scope") if DELETE is added.
  • Persistent (immutable) hash trie: A persistent data structure shares unchanged subtrees across versions automatically, making BEGIN, ROLLBACK, and COMMIT all O(1) pointer operations at the expense of O(log n) per GET and SET.

Follow-up questions

  • How would you add an O(1) DELETE key command that participates cleanly in nested rollbacks? Handle DELETE identically to SET: if self.undo_logs is non-empty and key not in self.undo_logs[-1], store self.data.get(key, _ABSENT) in self.undo_logs[-1], and then remove key from self.data via self.data.pop(key, None). During rollback(), use self.data.pop(key, None) when old_value is _ABSENT (since a DELETE inside that scope might already have removed key) and self.data[key] = old_value otherwise — keeping DELETE at O(1) average time.
  • How could you support an O(1) COUNT value query returning how many keys currently map to a given value? Keep a companion counter dictionary self.value_counts: Dict[str, int] tracking how many live keys in self.data currently hold each value. Funnel every mutation of self.data (inside set, delete, and rollback) through a single helper _apply_mutation(key, new_val_or_absent) that decrements the count of the outgoing value (if present) and increments the count of the incoming value (if not _ABSENT), making COUNT value a single O(1) lookup self.value_counts.get(value, 0).
  • What changes if COMMIT should merge only the innermost transaction into its parent instead of closing all open scopes? Pop inner_log = self.undo_logs.pop(). If self.undo_logs is now empty, those writes already sit permanently in self.data and nothing else is needed; otherwise merge inner_log into parent_log = self.undo_logs[-1] by setting parent_log[k] = old_val only when k not in parent_log (preserving the older pre-parent value whenever both scopes modified k), which runs in O(k) time.

Follow-up questions

Similar questions

More Applied Intuition interview questions

All 48 Applied Intuition questions →