In-Memory Relational Table with Transaction Rollback

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Build an in-memory tabular store initialized with an ordered list of string column names columns and keyed by a unique integer primary key row_id. Every data-modifying call must run inside an open transaction; callers can commit an open transaction to keep its edits permanently or roll it back to restore the exact table state from when the transaction opened.

Implement the driver function run_transactional_table (backed by a TransactionalTable class):

def run_transactional_table(
    columns: List[str],
    operations: List[str],
    arguments: List[List],
) -> List:

run_transactional_table constructs a fresh table with columns, dispatches each method name in operations with its positional argument list from arguments, and returns a list of the corresponding return values. Support these methods and exact behaviors:

  • begin() -> bool: Opens a new transaction and returns True. Because nested transactions are unsupported, returns False if a transaction is already open.
  • commit() -> bool: Finalizes all modifications performed in the open transaction, closes the transaction, and returns True. Returns False when no transaction is open.
  • rollback() -> bool: Reverts every row insertion, cell edit, deletion, and replacement performed since begin() was called, closes the transaction, and returns True. Returns False when no transaction is open.
  • insert_row(row_id: int, values: dict[str, str]) -> bool: Validates that a transaction is open, row_id does not currently exist, and every key in values belongs to columns; if any check fails, leaves the table untouched and returns False. Otherwise inserts row_id, defaulting any omitted schema columns to "", and returns True.
  • update_cell(row_id: int, column: str, value: str) -> bool: Returns False if no transaction is open, row_id does not exist, or column is not in columns (note that "id" is not a mutable schema column). Otherwise sets that cell to value and returns True.
  • delete_row(row_id: int) -> bool: Returns False if no transaction is open or row_id does not exist. Otherwise removes row_id and returns True.
  • find_and_replace(column: str, target: str, replacement: str) -> int: Returns -1 if no transaction is open or column is not in columns. If target == "", matches nothing and returns 0. Otherwise replaces every non-overlapping occurrence of target with replacement in each row's column cell and returns how many cells actually changed text.
  • serialize() -> str: Exports the current table state (whether or not a transaction is open, including uncommitted edits) as \n-separated CSV lines with no trailing newline. Line 1 is id,<col_1>,<col_2>,... in schema order, followed by rows sorted by ascending integer row_id. Any header or cell containing ,, ", \n, or \r must follow RFC 4180 quoting (double internal " to "" and wrap the field in "...").

Examples

Example 1

Input:
  columns = ["ticker", "desk"]
  operations = [
      "insert_row",
      "begin", "insert_row", "insert_row", "find_and_replace", "commit",
      "begin", "update_cell", "delete_row", "rollback",
      "serialize",
  ]
  arguments = [
      [10, {"ticker": "NVDA", "desk": "Quant"}],
      [], [10, {"ticker": "NVDA", "desk": "Quant"}], [2, {"ticker": "MSFT", "desk": "Quant"}],
      ["desk", "Quant", "Systematic"], [],
      [], [2, "desk", "Macro"], [10], [],
      [],
  ]
Output:
  [
      False,
      True, True, True, 2, True,
      True, True, True, True,
      "id,ticker,desk\n2,MSFT,Systematic\n10,NVDA,Systematic",
  ]

The initial insert_row fails (False) because no transaction is open yet. Transaction 1 inserts rows 10 and 2, rewrites "Quant" to "Systematic" across 2 cells, and commits. Transaction 2 updates row 2 and deletes row 10, then rolls back so both committed rows are restored; serialize outputs row 2 before row 10 in numeric ID order.

Example 2

Input:
  columns = ["memo", "tag"]
  operations = ["begin", "insert_row", "serialize", "rollback", "serialize"]
  arguments = [[], [7, {"memo": "limit, fast"}], [], [], []]
Output:
  [True, True, 'id,memo,tag\n7,"limit, fast",', True, "id,memo,tag"]

Inside the open transaction, row 7 omits "tag" (defaulting to "") and stores a comma inside "memo", so mid-transaction serialize() quotes "limit, fast". Calling rollback() discards the uncommitted insert, leaving only the header line "id,memo,tag".

Constraints

  • 1 <= len(columns) <= 50; column names are distinct strings and exclude "id".
  • len(operations) == len(arguments) and 0 <= len(operations) <= 10^4.
  • Only one transaction can be open at any time.

Step-by-step walkthrough

  1. Understand the table rules and boundary details

    We are building an in-memory relational table keyed by unique integer row_ids, with a fixed ordered list of string columns:

    • Transaction lifecycle: Only one transaction can be open at a time. begin() opens one (returning False if already open); commit() makes its edits permanent; rollback() rewinds the table to the exact state at begin() (both return False when no transaction is open).
    • Writes require an open transaction: Outside a transaction, insert_row, update_cell, and delete_row return False, while find_and_replace returns -1.
    • Reads happen anytime: serialize() works both outside and inside an open transaction (Example 2 calls serialize() mid-transaction and sees uncommitted rows), sorting rows by integer row_id ascending (2 before 10 in Example 1) and quoting CSV special characters ("limit, fast" in Example 2).
  2. Why snapshotting the whole table is wasteful

    The simplest way to support rollback() is to copy.deepcopy(self.rows) on every begin(): if the user calls rollback(), swap the copy back in; if they call commit(), throw the copy away.

    That works on tiny tables, and makes a great test oracle! Its flaw is cost: if a table holds 1,000,000 rows and a transaction edits one single cell, begin() still copies all 1,000,000 rows (O(R * C) time and memory). Almost all that copying is wasted.

  3. Key idea: first-touch before-images per row

    Instead of copying the whole table up front, we copy a row lazily — only the very first time the open transaction is about to touch that row_id — into a dictionary self.before_images:

    self.before_images[row_id] = dict(self.rows[row_id])   (if row_id existed at begin())
    self.before_images[row_id] = None                      (if row_id did NOT exist at begin())
    

    Trace what happens if a single transaction touches the same row_id several times:

    At begin():                   rows[2] = {"desk": "Quant"}       before_images = {}
    1st edit: update(2, "Macro")  save first! -> before_images = {2: {"desk": "Quant"}}
                                  rows[2] = {"desk": "Macro"}
    2nd edit: delete_row(2)       2 is ALREADY in before_images -> do NOT overwrite!
                                  rows[2] deleted
    On rollback():                restore rows[2] = before_images[2] = {"desk": "Quant"}  (exact!)
    

    Two properties make this design rock-solid:

    1. Memory scales with touched rows t, not table size R: Updating 3 rows in a million-row table stores only 3 row copies.
    2. Rollback order does not matter: Because each entry records the row's exact state at begin() (or None if it was absent), restoring self.before_images.items() in any order reconstructs the exact table from begin().
  4. Code transaction lifecycle: begin, commit, and rollback

    Let's write TransactionalTable.__init__, _record_before_image, begin, commit, and rollback. Two details inside _record_before_image and rollback prevent subtle bugs:

    • Shallow-copy the row dict (dict(self.rows[row_id])): Cell values are immutable Python strings, so dict(...) creates an independent dictionary. Saving self.rows[row_id] directly without dict(...) would save a shared reference that gets mutated by update_cell!
    • Use self.rows.pop(row_id, None) when original_row is None: If a transaction inserts row 3 (before_images[3] = None) and then deletes row 3 before rolling back, row 3 is already absent from self.rows; pop(row_id, None) avoids a KeyError.
    class TransactionalTable:
        def __init__(self, columns: List[str]):
            # columns: schema column names in fixed display order, e.g. ["ticker", "desk"]
            self.columns: List[str] = list(columns)
            # column_set: set of valid schema column names for O(1) validation checks
            self.column_set: Set[str] = set(columns)
            # rows: dict mapping row_id -> {col_name: cell_str}, e.g. {10: {"ticker": "NVDA"}}
            self.rows: Dict[int, Dict[str, str]] = {}
    
            self.in_transaction: bool = False
            # before_images: undo map for the active transaction mapping
            #   row_id -> shallow copy of row dict as it stood at begin(),
            #             or None if `row_id` did not exist when begin() started.
            self.before_images: Dict[int, Optional[Dict[str, str]]] = {}
    
        def _record_before_image(self, row_id: int) -> None:
            """Save `row_id`'s pre-transaction state ONLY on the first touch in this transaction."""
            # Never overwrite an existing entry: later edits in the same transaction must
            # still roll back all the way to the state at `begin()`, not an intermediate state.
            if row_id in self.before_images:
                return
            if row_id in self.rows:
                # Copy the row dict (`dict(...)`) so future cell updates do not mutate our backup.
                self.before_images[row_id] = dict(self.rows[row_id])
            else:
                self.before_images[row_id] = None
    
        def begin(self) -> bool:
            if self.in_transaction:
                return False
            self.in_transaction = True
            self.before_images = {}
            return True
    
        def commit(self) -> bool:
            if not self.in_transaction:
                return False
            # Live edits are already in `self.rows`; discarding `before_images` makes them permanent.
            self.in_transaction = False
            self.before_images = {}
            return True
    
        def rollback(self) -> bool:
            if not self.in_transaction:
                return False
            for row_id, original_row in self.before_images.items():
                if original_row is None:
                    # Row did not exist at `begin()`; `pop(..., None)` also handles a row
                    # that was inserted and then deleted within this same transaction.
                    self.rows.pop(row_id, None)
                else:
                    self.rows[row_id] = original_row
            self.in_transaction = False
            self.before_images = {}
            return True
    
  5. Code row writes with validate-first discipline

    Every write method follows the exact same three-step discipline:

    1. Validate transaction state, row_id existence, and schema columns first.
    2. Record the before-image of row_id.
    3. Mutate self.rows.

    In insert_row, checking every key in values against self.column_set before writing guarantees that an invalid column like {"ticker": "NVDA", "unknown": "X"} rejects the entire insert without leaving a half-inserted row or a bogus undo entry behind. Also note that "id" is not in self.column_set, so update_cell(10, "id", "99") is automatically rejected.

        def insert_row(self, row_id: int, values: Dict[str, str]) -> bool:
            # Phase 1: Validate active transaction, unique row_id, and every supplied column name.
            if not self.in_transaction or row_id in self.rows:
                return False
            for column in values:
                if column not in self.column_set:
                    return False
    
            # Phase 2: Build complete row (unspecified schema columns default to ""), save backup, write.
            new_row: Dict[str, str] = {}
            for column in self.columns:
                new_row[column] = values.get(column, "")
            self._record_before_image(row_id)
            self.rows[row_id] = new_row
            return True
    
        def update_cell(self, row_id: int, column: str, value: str) -> bool:
            if not self.in_transaction or row_id not in self.rows or column not in self.column_set:
                return False
            self._record_before_image(row_id)
            self.rows[row_id][column] = value
            return True
    
        def delete_row(self, row_id: int) -> bool:
            if not self.in_transaction or row_id not in self.rows:
                return False
            self._record_before_image(row_id)
            del self.rows[row_id]
            return True
    
  6. Code find_and_replace, CSV quoting, and the replay driver

    In find_and_replace(column, target, replacement):

    • Missing transaction or invalid column returns -1 (not False!).
    • If target == "", we return 0 immediately because Python's "".replace("", "X") turns empty strings into "X".
    • For each row, we compute new_value = old_value.replace(target, replacement) and only save a before-image and increment modified_cells when new_value != old_value (which also handles target == replacement returning 0).

    In serialize(), Example 2 shows standard RFC 4180 CSV quoting (7,"limit, fast",): whenever a field contains a comma ,, a double quote ", or a line break (\n or \r), we double internal quotes (" -> "") and wrap the field in "...".

    def _format_csv_field(text: str) -> str:
        """Apply standard RFC 4180 CSV escaping when a field contains `,`, `"`, or a newline."""
        # Double internal quotes (`"` -> `""`) and wrap the field in outer quotes.
        if "," in text or '"' in text or "\n" in text or "\r" in text:
            return '"' + text.replace('"', '""') + '"'
        return text
    
        def find_and_replace(self, column: str, target: str, replacement: str) -> int:
            if not self.in_transaction or column not in self.column_set:
                return -1
            # Guard empty `target`: Python's `"".replace("", "x")` inserts `"x"` into empty strings,
            # whereas an empty search pattern should match nothing.
            if target == "":
                return 0
    
            modified_cells = 0
            for row_id, row in self.rows.items():
                old_value = row[column]
                new_value = old_value.replace(target, replacement)
                # Only record undo state and count the cell if its text actually changed.
                if new_value != old_value:
                    self._record_before_image(row_id)
                    row[column] = new_value
                    modified_cells += 1
            return modified_cells
    
        def serialize(self) -> str:
            header_fields = ["id"]
            for column in self.columns:
                header_fields.append(_format_csv_field(column))
            lines = [",".join(header_fields)]
    
            # Sort keys as integers (`2` before `10`), not in insertion or string order.
            for row_id in sorted(self.rows):
                row_fields = [str(row_id)]
                for column in self.columns:
                    row_fields.append(_format_csv_field(self.rows[row_id][column]))
                lines.append(",".join(row_fields))
            return "\n".join(lines)
    

    Finally, run_transactional_table dispatches each operation name to TransactionalTable and collects the return values:

    def run_transactional_table(
        columns: List[str],
        operations: List[str],
        arguments: List[List],
    ) -> List:
        table = TransactionalTable(columns)
        results: List[Any] = []
        for op, args in zip(operations, arguments):
            if op == "begin":
                results.append(table.begin())
            elif op == "commit":
                results.append(table.commit())
            elif op == "rollback":
                results.append(table.rollback())
            elif op == "insert_row":
                results.append(table.insert_row(args[0], args[1]))
            elif op == "update_cell":
                results.append(table.update_cell(args[0], args[1], args[2]))
            elif op == "delete_row":
                results.append(table.delete_row(args[0]))
            elif op == "find_and_replace":
                results.append(table.find_and_replace(args[0], args[1], args[2]))
            elif op == "serialize":
                results.append(table.serialize())
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    
  7. Trace Example 1 and Example 2 step by step

    Let's trace self.rows and self.before_images through Example 1 (columns = ["ticker", "desk"]):

    Call                                     Return  rows                             before_images
    ---------------------------------------  ------  -------------------------------  --------------------------
    insert_row(10, {NVDA, Quant})            False   {}                               {}   (no open txn!)
    begin()                                  True    {}                               {}
    insert_row(10, {NVDA, Quant})            True    {10: NVDA/Quant}                 {10: None}
    insert_row(2, {MSFT, Quant})             True    {10: NVDA/Quant, 2: MSFT/Quant}  {10: None, 2: None}
    find_and_replace("desk",                         {10: NVDA/Systematic,            {10: None, 2: None}
                     "Quant", "Systematic")  2        2: MSFT/Systematic}             (already recorded!)
    commit()                                 True    {10: NVDA/Systematic,            {}   (changes permanent!)
                                                      2: MSFT/Systematic}
    begin()                                  True    (same)                           {}
    update_cell(2, "desk", "Macro")          True    {10: NVDA/Systematic,            {2: MSFT/Systematic}
                                                      2: MSFT/Macro}
    delete_row(10)                           True    {2: MSFT/Macro}                  {2: MSFT/Systematic,
                                                                                       10: NVDA/Systematic}
    rollback()                               True    {10: NVDA/Systematic,            {}   (both restored!)
                                                      2: MSFT/Systematic}
    serialize()                              "id,ticker,desk\n2,MSFT,Systematic\n10,NVDA,Systematic"
    

    And in Example 2 (columns = ["memo", "tag"]):

    • begin() -> True; insert_row(7, {"memo": "limit, fast"}) -> True (before_images = {7: None}, "tag" defaults to "").
    • serialize() runs before rollback, quoting the comma: 'id,memo,tag\n7,"limit, fast",'.
    • rollback() sees before_images[7] is None and pops row 7, so the second serialize() returns 'id,memo,tag'.
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _format_csv_field(text: str) -> str:
        """Apply standard RFC 4180 CSV escaping when a field contains `,`, `"`, or a newline."""
        # Double internal quotes (`"` -> `""`) and wrap the field in outer quotes.
        if "," in text or '"' in text or "\n" in text or "\r" in text:
            return '"' + text.replace('"', '""') + '"'
        return text
    
    
    class TransactionalTable:
        def __init__(self, columns: List[str]):
            # columns: schema column names in fixed display order, e.g. ["ticker", "desk"]
            self.columns: List[str] = list(columns)
            # column_set: set of valid schema column names for O(1) validation checks
            self.column_set: Set[str] = set(columns)
            # rows: dict mapping row_id -> {col_name: cell_str}, e.g. {10: {"ticker": "NVDA"}}
            self.rows: Dict[int, Dict[str, str]] = {}
    
            self.in_transaction: bool = False
            # before_images: undo map for the active transaction mapping
            #   row_id -> shallow copy of row dict as it stood at begin(),
            #             or None if `row_id` did not exist when begin() started.
            self.before_images: Dict[int, Optional[Dict[str, str]]] = {}
    
        def _record_before_image(self, row_id: int) -> None:
            """Save `row_id`'s pre-transaction state ONLY on the first touch in this transaction."""
            # Never overwrite an existing entry: later edits in the same transaction must
            # still roll back all the way to the state at `begin()`, not an intermediate state.
            if row_id in self.before_images:
                return
            if row_id in self.rows:
                # Copy the row dict (`dict(...)`) so future cell updates do not mutate our backup.
                self.before_images[row_id] = dict(self.rows[row_id])
            else:
                self.before_images[row_id] = None
    
        # ---------------- Transaction lifecycle ----------------
        def begin(self) -> bool:
            if self.in_transaction:
                return False
            self.in_transaction = True
            self.before_images = {}
            return True
    
        def commit(self) -> bool:
            if not self.in_transaction:
                return False
            # Live edits are already in `self.rows`; discarding `before_images` makes them permanent.
            self.in_transaction = False
            self.before_images = {}
            return True
    
        def rollback(self) -> bool:
            if not self.in_transaction:
                return False
            for row_id, original_row in self.before_images.items():
                if original_row is None:
                    # Row did not exist at `begin()`; `pop(..., None)` also handles a row
                    # that was inserted and then deleted within this same transaction.
                    self.rows.pop(row_id, None)
                else:
                    self.rows[row_id] = original_row
            self.in_transaction = False
            self.before_images = {}
            return True
    
        # ---------------- Validated write operations ----------------
        def insert_row(self, row_id: int, values: Dict[str, str]) -> bool:
            # Phase 1: Validate active transaction, unique row_id, and every supplied column name.
            if not self.in_transaction or row_id in self.rows:
                return False
            for column in values:
                if column not in self.column_set:
                    return False
    
            # Phase 2: Build complete row (unspecified schema columns default to ""), save backup, write.
            new_row: Dict[str, str] = {}
            for column in self.columns:
                new_row[column] = values.get(column, "")
            self._record_before_image(row_id)
            self.rows[row_id] = new_row
            return True
    
        def update_cell(self, row_id: int, column: str, value: str) -> bool:
            if not self.in_transaction or row_id not in self.rows or column not in self.column_set:
                return False
            self._record_before_image(row_id)
            self.rows[row_id][column] = value
            return True
    
        def delete_row(self, row_id: int) -> bool:
            if not self.in_transaction or row_id not in self.rows:
                return False
            self._record_before_image(row_id)
            del self.rows[row_id]
            return True
    
        def find_and_replace(self, column: str, target: str, replacement: str) -> int:
            if not self.in_transaction or column not in self.column_set:
                return -1
            # Guard empty `target`: Python's `"".replace("", "x")` inserts `"x"` into empty strings,
            # whereas an empty search pattern should match nothing.
            if target == "":
                return 0
    
            modified_cells = 0
            for row_id, row in self.rows.items():
                old_value = row[column]
                new_value = old_value.replace(target, replacement)
                # Only record undo state and count the cell if its text actually changed.
                if new_value != old_value:
                    self._record_before_image(row_id)
                    row[column] = new_value
                    modified_cells += 1
            return modified_cells
    
        # ---------------- Read / export ----------------
        def serialize(self) -> str:
            header_fields = ["id"]
            for column in self.columns:
                header_fields.append(_format_csv_field(column))
            lines = [",".join(header_fields)]
    
            # Sort keys as integers (`2` before `10`), not in insertion or string order.
            for row_id in sorted(self.rows):
                row_fields = [str(row_id)]
                for column in self.columns:
                    row_fields.append(_format_csv_field(self.rows[row_id][column]))
                lines.append(",".join(row_fields))
            return "\n".join(lines)
    
    
    def run_transactional_table(
        columns: List[str],
        operations: List[str],
        arguments: List[List],
    ) -> List:
        table = TransactionalTable(columns)
        results: List[Any] = []
        for op, args in zip(operations, arguments):
            if op == "begin":
                results.append(table.begin())
            elif op == "commit":
                results.append(table.commit())
            elif op == "rollback":
                results.append(table.rollback())
            elif op == "insert_row":
                results.append(table.insert_row(args[0], args[1]))
            elif op == "update_cell":
                results.append(table.update_cell(args[0], args[1], args[2]))
            elif op == "delete_row":
                results.append(table.delete_row(args[0]))
            elif op == "find_and_replace":
                results.append(table.find_and_replace(args[0], args[1], args[2]))
            elif op == "serialize":
                results.append(table.serialize())
            else:
                raise ValueError(f"unknown operation: {op}")
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of editing a giant binder of 1,000,000 portfolio pages inside a transaction (a group of edits treated as one all-or-nothing unit that either saves completely on commit or rewinds completely on rollback). Instead of standing at a photocopier and duplicating all 1,000,000 pages every time begin() starts, you only photocopy a page the very first time your pen is about to touch that specific page! In database internals, that backup map is a before-image undo log (a dictionary mapping each modified row_id to a copy of the row as it existed at begin(), or None if the row did not exist yet).

Why do simpler approaches fall short? Editing self.rows in place with no backup makes rollback() impossible, while deep-copying the entire table on every begin() wastes O(R * C) time and memory whenever a transaction edits just one or two rows out of millions. Recording a row's before-image on first touch — and refusing to overwrite that backup on second or third edits in the same transaction — keeps begin() and commit() at O(1) while rollback() only visits the t rows the transaction actually modified.

Here is how before_images handles repeated edits, an insert, and a rollback() starting from rows = {2: {"desk": "Systematic"}}:

begin()                           -> rows = {2: "Systematic"}             before_images = {}
update_cell(2, "desk", "Macro")   -> rows = {2: "Macro"}                  before_images = {2: {"desk": "Systematic"}}
update_cell(2, "desk", "Flow")    -> rows = {2: "Flow"}                   before_images = {2: {"desk": "Systematic"}} (kept!)
insert_row(7, {"desk": "Options"})-> rows = {2: "Flow", 7: "Options"}     before_images = {2: {"desk": "Systematic"}, 7: None}
rollback()                        -> restore 2, pop 7 -> rows = {2: "Systematic"}  (exact state at begin()!)

Complexity

Let R be the current number of rows in the table, C be the number of schema columns, and t (t <= R) be the number of distinct row_ids modified during the active transaction.

  • begin and commit: O(1) time, because both only flip self.in_transaction and reset self.before_images = {}.
  • insert_row: O(C + len(values)) time to validate every key in values against self.column_set and populate all C schema columns.
  • update_cell and delete_row: O(C) time on the first modification to row_id in a transaction (to shallow-copy its C-column dictionary into before_images), and O(1) average time on any subsequent modification to the same row_id in that transaction.
  • rollback: O(t) time, because we iterate over the t entries in self.before_images and reassign or pop each row dictionary in O(1) average time without re-copying.
  • find_and_replace: O(R * L + m * C) time, where L bounds cell string length before and after replacement and m is the number of rows modified for the first time in this transaction, because every row's cell in column is scanned with str.replace.
  • serialize: O(R log R + B) time, where R log R sorts the integer row_id keys and B is the total character length of the formatted CSV output.
  • Space: O(R * C) for the live table plus O(t * C) for the active transaction's before_images (compared to O(R * C) extra on every transaction for a full-table snapshot).

Edge cases

  • Writes outside a transaction: insert_row, update_cell, and delete_row return False, find_and_replace returns -1, and neither rows nor before_images changes.
  • Double begin(), or commit() / rollback() with no active transaction: Return False without side effects.
  • Unspecified vs unknown columns in insert_row: Omitted schema columns default to "" (as with "tag" in Example 2), whereas any extra key outside self.column_set rejects the entire insert before any state is mutated.
  • Updating "id" via update_cell: "id" is not in self.column_set, so update_cell(2, "id", ...) cleanly returns False.
  • Delete then re-insert the same row_id in one transaction: delete_row saves the original row dict into before_images[row_id]; the subsequent insert_row sees row_id in self.before_images and leaves that backup intact, so rollback() restores the original pre-transaction row.
  • Insert then delete the same row_id in one transaction: insert_row records before_images[row_id] = None, delete_row removes row_id from self.rows, and rollback() uses self.rows.pop(row_id, None) without raising KeyError.
  • find_and_replace with target == replacement or target == "": Neither changes any cell text, so 0 cells are counted and no unnecessary before-images are saved.
  • CSV special characters and integer ID ordering: Values containing ,, ", \n, or \r are wrapped in double quotes with internal quotes doubled ("say ""hi"""), and sorted(self.rows) orders row_id = 2 before row_id = 10 (Example 1).

Common mistakes

  • Mutating state before finishing validation: Inserting valid columns into self.rows[row_id] before discovering an invalid column name leaves corrupted partial data behind on a False return.
  • Storing self.rows[row_id] in before_images without dict(...): Saving a direct dictionary reference means update_cell mutates both the live row and the backup simultaneously, rendering rollback() useless.
  • Overwriting before_images[row_id] on every edit: Without if row_id in self.before_images: return, updating a cell twice and rolling back restores the first update instead of the state at begin().
  • Forgetting to delete newly inserted rows on rollback(): If before_images only stores pre-existing rows and ignores inserts, rollback() leaves uncommitted inserts sitting in the table (breaking Example 2).
  • Formatting CSV with raw ",".join(...): Any cell containing a comma (like "limit, fast" in Example 2) splits into extra CSV columns unless RFC 4180 quoting is applied.
  • Sorting row_ids lexicographically ("10" before "2"): Convert row_id to str after sorted(self.rows), not before.

Alternative approaches

  • Full-table copy.deepcopy on begin(): Trivial to write (5 lines for begin/commit/rollback), great as a brute-force reference test, but costs O(R * C) time and memory per transaction even for 1-row edits.
  • Operation-level inverse undo log: Append inverse commands such as ("delete", row_id), ("set_cell", row_id, col, old_val), or ("restore_row", row_id, old_row) onto a stack and replay reversed(log) during rollback(). That saves memory on very wide rows (C huge) when only one cell changes, at the cost of O(operations) log growth when the same cell is updated repeatedly.
  • Python's built-in csv.writer: Writing rows into an io.StringIO buffer with csv.writer(buf, lineterminator="\n") implements identical RFC 4180 quoting using the standard library (remembering to strip the trailing "\n").

Follow-up questions

  • How could you generalize the single-level undo map so callers can open nested transactions or roll back to named savepoints? Replace the single self.before_images dictionary with a stack of undo dictionaries — pushing a fresh {} on every begin() (or savepoint, a named inner checkpoint that can roll back without aborting outer work). Every write records its before-image into the top dictionary stack[-1] if row_id is not already in stack[-1]. Calling rollback() restores from stack.pop(); calling commit() on an inner level pops child = stack.pop() and merges each (row_id, img) into the parent stack[-1] only if row_id not in stack[-1] so the parent retains the oldest pre-parent image.
  • What changes are needed so multiple threads can run read snapshots and write transactions concurrently without blocking readers? Adopt MVCC (Multi-Version Concurrency Control) — keeping an ordered chain of immutable row versions (created_tx, expired_tx, row_dict) per row_id alongside a monotonic transaction counter. Each begin() captures a read_ts snapshot timestamp and reads the latest version committed at or before read_ts (plus its own private write set), allowing serialize() and queries to run lock-free alongside concurrent writers! At commit(), acquire brief per-row latches (or a short commit lock) for first-committer-wins validation: abort if any written row_id gained a newer committed version after read_ts, otherwise publish the buffered versions at a new commit_ts and reclaim versions older than the oldest active read_ts.
  • How would you accelerate find_and_replace on a multi-million-row table so substring replacements do not scan every row? Exact whole-cell replacements only need a hash index col_index[col][cell_value] -> set_of_row_ids to visit matching rows in O(matches) time. Because find_and_replace targets arbitrary substrings, maintain an n-gram inverted index (such as a trigram index mapping every 3-character slice like "Qua" to the set of row_ids whose cell contains it): for len(target) >= 3, intersect the posting sets of target's trigrams to narrow millions of rows down to a small candidate list, verify target in cell on those candidates, and update old and new trigrams whenever a cell is inserted, updated, deleted, or rolled back.

Follow-up questions

Similar questions

More Addepar interview questions

All 3 Addepar questions →