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 returnsTrue. Because nested transactions are unsupported, returnsFalseif a transaction is already open.commit() -> bool: Finalizes all modifications performed in the open transaction, closes the transaction, and returnsTrue. ReturnsFalsewhen no transaction is open.rollback() -> bool: Reverts every row insertion, cell edit, deletion, and replacement performed sincebegin()was called, closes the transaction, and returnsTrue. ReturnsFalsewhen no transaction is open.insert_row(row_id: int, values: dict[str, str]) -> bool: Validates that a transaction is open,row_iddoes not currently exist, and every key invaluesbelongs tocolumns; if any check fails, leaves the table untouched and returnsFalse. Otherwise insertsrow_id, defaulting any omitted schema columns to"", and returnsTrue.update_cell(row_id: int, column: str, value: str) -> bool: ReturnsFalseif no transaction is open,row_iddoes not exist, orcolumnis not incolumns(note that"id"is not a mutable schema column). Otherwise sets that cell tovalueand returnsTrue.delete_row(row_id: int) -> bool: ReturnsFalseif no transaction is open orrow_iddoes not exist. Otherwise removesrow_idand returnsTrue.find_and_replace(column: str, target: str, replacement: str) -> int: Returns-1if no transaction is open orcolumnis not incolumns. Iftarget == "", matches nothing and returns0. Otherwise replaces every non-overlapping occurrence oftargetwithreplacementin each row'scolumncell 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 isid,<col_1>,<col_2>,...in schema order, followed by rows sorted by ascending integerrow_id. Any header or cell containing,,",\n, or\rmust 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)and0 <= len(operations) <= 10^4.- Only one transaction can be open at any time.
Step-by-step walkthrough
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 stringcolumns:- Transaction lifecycle: Only one transaction can be open at a time.
begin()opens one (returningFalseif already open);commit()makes its edits permanent;rollback()rewinds the table to the exact state atbegin()(both returnFalsewhen no transaction is open). - Writes require an open transaction: Outside a transaction,
insert_row,update_cell, anddelete_rowreturnFalse, whilefind_and_replacereturns-1. - Reads happen anytime:
serialize()works both outside and inside an open transaction (Example 2 callsserialize()mid-transaction and sees uncommitted rows), sorting rows by integerrow_idascending (2before10in Example 1) and quoting CSV special characters ("limit, fast"in Example 2).
- Transaction lifecycle: Only one transaction can be open at a time.
Why snapshotting the whole table is wasteful
The simplest way to support
rollback()is tocopy.deepcopy(self.rows)on everybegin(): if the user callsrollback(), swap the copy back in; if they callcommit(), 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,000rows and a transaction edits one single cell,begin()still copies all1,000,000rows (O(R * C)time and memory). Almost all that copying is wasted.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 dictionaryself.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_idseveral 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:
- Memory scales with touched rows
t, not table sizeR: Updating3rows in a million-row table stores only3row copies. - Rollback order does not matter: Because each entry records the row's exact state at
begin()(orNoneif it was absent), restoringself.before_images.items()in any order reconstructs the exact table frombegin().
- Memory scales with touched rows
Code transaction lifecycle: begin, commit, and rollback
Let's write
TransactionalTable.__init__,_record_before_image,begin,commit, androllback. Two details inside_record_before_imageandrollbackprevent subtle bugs:- Shallow-copy the row dict (
dict(self.rows[row_id])): Cell values are immutable Python strings, sodict(...)creates an independent dictionary. Savingself.rows[row_id]directly withoutdict(...)would save a shared reference that gets mutated byupdate_cell! - Use
self.rows.pop(row_id, None)whenoriginal_row is None: If a transaction inserts row3(before_images[3] = None) and then deletes row3before rolling back, row3is already absent fromself.rows;pop(row_id, None)avoids aKeyError.
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- Shallow-copy the row dict (
Code row writes with validate-first discipline
Every write method follows the exact same three-step discipline:
- Validate transaction state,
row_idexistence, and schema columns first. - Record the before-image of
row_id. - Mutate
self.rows.
In
insert_row, checking every key invaluesagainstself.column_setbefore 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 inself.column_set, soupdate_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- Validate transaction state,
Code find_and_replace, CSV quoting, and the replay driver
In
find_and_replace(column, target, replacement):- Missing transaction or invalid
columnreturns-1(notFalse!). - If
target == "", we return0immediately 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 incrementmodified_cellswhennew_value != old_value(which also handlestarget == replacementreturning0).
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 (\nor\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 textdef 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_tabledispatches each operation name toTransactionalTableand 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- Missing transaction or invalid
Trace Example 1 and Example 2 step by step
Let's trace
self.rowsandself.before_imagesthrough 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()seesbefore_images[7] is Noneand pops row7, so the secondserialize()returns'id,memo,tag'.
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.
beginandcommit:O(1)time, because both only flipself.in_transactionand resetself.before_images = {}.insert_row:O(C + len(values))time to validate every key invaluesagainstself.column_setand populate allCschema columns.update_cellanddelete_row:O(C)time on the first modification torow_idin a transaction (to shallow-copy itsC-column dictionary intobefore_images), andO(1)average time on any subsequent modification to the samerow_idin that transaction.rollback:O(t)time, because we iterate over thetentries inself.before_imagesand reassign orpopeach row dictionary inO(1)average time without re-copying.find_and_replace:O(R * L + m * C)time, whereLbounds cell string length before and after replacement andmis the number of rows modified for the first time in this transaction, because every row's cell incolumnis scanned withstr.replace.serialize:O(R log R + B)time, whereR log Rsorts the integerrow_idkeys andBis the total character length of the formatted CSV output.- Space:
O(R * C)for the live table plusO(t * C)for the active transaction'sbefore_images(compared toO(R * C)extra on every transaction for a full-table snapshot).
Edge cases
- Writes outside a transaction:
insert_row,update_cell, anddelete_rowreturnFalse,find_and_replacereturns-1, and neitherrowsnorbefore_imageschanges. - Double
begin(), orcommit()/rollback()with no active transaction: ReturnFalsewithout side effects. - Unspecified vs unknown columns in
insert_row: Omitted schema columns default to""(as with"tag"in Example 2), whereas any extra key outsideself.column_setrejects the entire insert before any state is mutated. - Updating
"id"viaupdate_cell:"id"is not inself.column_set, soupdate_cell(2, "id", ...)cleanly returnsFalse. - Delete then re-insert the same
row_idin one transaction:delete_rowsaves the original row dict intobefore_images[row_id]; the subsequentinsert_rowseesrow_id in self.before_imagesand leaves that backup intact, sorollback()restores the original pre-transaction row. - Insert then delete the same
row_idin one transaction:insert_rowrecordsbefore_images[row_id] = None,delete_rowremovesrow_idfromself.rows, androllback()usesself.rows.pop(row_id, None)without raisingKeyError. find_and_replacewithtarget == replacementortarget == "": Neither changes any cell text, so0cells are counted and no unnecessary before-images are saved.- CSV special characters and integer ID ordering: Values containing
,,",\n, or\rare wrapped in double quotes with internal quotes doubled ("say ""hi"""), andsorted(self.rows)ordersrow_id = 2beforerow_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 aFalsereturn. - Storing
self.rows[row_id]inbefore_imageswithoutdict(...): Saving a direct dictionary reference meansupdate_cellmutates both the live row and the backup simultaneously, renderingrollback()useless. - Overwriting
before_images[row_id]on every edit: Withoutif row_id in self.before_images: return, updating a cell twice and rolling back restores the first update instead of the state atbegin(). - Forgetting to delete newly inserted rows on
rollback(): Ifbefore_imagesonly 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"): Convertrow_idtostraftersorted(self.rows), not before.
Alternative approaches
- Full-table
copy.deepcopyonbegin(): Trivial to write (5lines forbegin/commit/rollback), great as a brute-force reference test, but costsO(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 replayreversed(log)duringrollback(). That saves memory on very wide rows (Chuge) when only one cell changes, at the cost ofO(operations)log growth when the same cell is updated repeatedly. - Python's built-in
csv.writer: Writing rows into anio.StringIObuffer withcsv.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_imagesdictionary with a stack of undo dictionaries — pushing a fresh{}on everybegin()(or savepoint, a named inner checkpoint that can roll back without aborting outer work). Every write records its before-image into the top dictionarystack[-1]ifrow_idis not already instack[-1]. Callingrollback()restores fromstack.pop(); callingcommit()on an inner level popschild = stack.pop()and merges each(row_id, img)into the parentstack[-1]only ifrow_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)perrow_idalongside a monotonic transaction counter. Eachbegin()captures aread_tssnapshot timestamp and reads the latest version committed at or beforeread_ts(plus its own private write set), allowingserialize()and queries to run lock-free alongside concurrent writers! Atcommit(), acquire brief per-row latches (or a short commit lock) for first-committer-wins validation: abort if any writtenrow_idgained a newer committed version afterread_ts, otherwise publish the buffered versions at a newcommit_tsand reclaim versions older than the oldest activeread_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_idsto visit matching rows inO(matches)time. Becausefind_and_replacetargets arbitrary substrings, maintain an n-gram inverted index (such as a trigram index mapping every 3-character slice like"Qua"to the set ofrow_ids whose cell contains it): forlen(target) >= 3, intersect the posting sets oftarget's trigrams to narrow millions of rows down to a small candidate list, verifytarget in cellon those candidates, and update old and new trigrams whenever a cell is inserted, updated, deleted, or rolled back.
Follow-up questions
- How could you generalize the single-level undo map so callers can open nested transactions or roll back to named savepoints?
- What changes are needed so multiple threads can run read snapshots and write transactions concurrently without blocking readers?
- How would you accelerate find_and_replace on a multi-million-row table so substring replacements do not scan every row?
Similar questions
- Global Event Ticketing and Seat Inventory Platform
- Rolling-Window Error Alerting by Endpoint Prefix
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance