Command-Pattern Undo and Redo Engine for Spreadsheets
Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a dependency-aware undo and redo engine for an in-memory spreadsheet using the Command pattern. Unlike a plain text buffer, edits in a spreadsheet propagate through formula graphs, row deletions break downstream references, multi-cell batches must succeed or roll back atomically, and external actions may not be reversible.
Data Model & Sheet Receiver
Rows are identified by stable string IDs (row_id), and cells are addressed by CellKey = Tuple[str, str] ((row_id, col)). Broken references evaluate to REF_ERROR = "#REF!".
Formula(refs: List[CellKey])- Immutable sum expression over its referenced
(row_id, col)keys (repeated keys contribute multiple times; an empty list sums to0). - If any referenced cell belongs to a deleted row—or itself evaluates to
"#REF!"—the formula evaluates to"#REF!".
- Immutable sum expression over its referenced
Spreadsheet(row_ids: List[str])- Stores
self.rowsas the current top-to-bottom display list of liverow_idstrings. has_row(row_id: str) -> bool: returnsTrueifrow_idis currently live, elseFalse.get(row_id: str, col: str): returns"#REF!"whenrow_idhas been deleted,0when(row_id, col)is empty on a live row, or the cell's numeric / evaluated formula result.snapshot() -> Dict[CellKey, object]: returns a dictionary of{ (row_id, col): evaluated_value }for every non-empty cell across live rows.
- Stores
Commands & Bounded History
Command- Base class defining class flags
undoable = Trueandinvalidates_history = False, along withexecute() -> Noneandundo() -> None.
- Base class defining class flags
SetCellCommand(sheet: Spreadsheet, row_id: str, col: str, content)- Writes a numeric value (
intorfloat), aFormula, orNone(clearing the cell) to(row_id, col)and recalculates downstream dependents. execute()must raiseValueErrorwithout modifying anything ifrow_idis not live or ifcontentis aFormulathat creates a self-reference or dependency cycle.undo()restores the cell's prior raw content and recalculates downstream dependents.
- Writes a numeric value (
DeleteRowCommand(sheet: Spreadsheet, row_id: str)execute()raisesValueErrorifrow_idis not live. Otherwise removesrow_idfromsheet.rowsand cell storage, detaches any formulas that lived insiderow_idso they no longer act as active listeners, and updates every external formula readingrow_id(including empty cells inrow_id) to"#REF!".undo()re-insertsrow_idat its former index insheet.rowswith all saved cells, reconnects its formulas, and recalculates downstream readers so"#REF!"values recover.
BatchCommand(commands: List[Command])- Raises
ValueErrorat construction if any child hasundoable == False. execute()runs children in order; if a child raisesValueError, every previously executed child in the batch is undone in reverse order andValueErroris re-raised.undo()reverts all children in reverse order as one step.
- Raises
PublishCommand(sheet: Spreadsheet, destination: list)- Non-undoable external export (
undoable = False,invalidates_history = False).execute()appendssheet.snapshot()todestinationwithout changing sheet state;undo()raisesRuntimeError.
- Non-undoable external export (
History(max_commands: int = 100)- Raises
ValueErrorifmax_commands < 0. run(command: Command) -> None: runscommand.execute()(leaving both stacks untouched ifValueErroris raised). Ifcommand.undoableisFalse, does not record the command—clearing both stacks whencommand.invalidates_historyisTrueand preserving both stacks otherwise. Ifcommand.undoableisTrue, pushes onto a bounded undo buffer of capacitymax_commands(dropping the oldest entry when full) and clears the redo stack.undo() -> bool: reverts the latest undoable command, moves it to the redo stack, and returnsTrue(Falsewhen nothing can be undone).redo() -> bool: re-executes the latest undone command, moves it back to the undo stack, and returnsTrue(Falsewhen nothing can be redone).
- Raises
Examples
Example 1
sheet = Spreadsheet(["hdr", "jan", "feb", "tot"])
history = History()
history.run(SetCellCommand(sheet, "jan", "price", 40))
history.run(SetCellCommand(sheet, "feb", "price", 60))
history.run(SetCellCommand(sheet, "tot", "price", Formula([("jan", "price"), ("feb", "price")])))
sheet.get("tot", "price") # -> 100
history.run(DeleteRowCommand(sheet, "feb"))
sheet.rows # -> ["hdr", "jan", "tot"]
sheet.get("feb", "price") # -> "#REF!"
sheet.get("tot", "price") # -> "#REF!"
history.undo() # -> True
sheet.rows # -> ["hdr", "jan", "feb", "tot"]
sheet.get("tot", "price") # -> 100
history.redo() # -> True
sheet.get("tot", "price") # -> "#REF!"
Walk-through: Deleting row "feb" removes it from sheet.rows and propagates "#REF!" into ("tot", "price") while keeping the reverse dependency edge from ("feb", "price") to ("tot", "price"). Undoing re-inserts "feb" at index 2 and restores ("tot", "price") to 100; redoing deletes "feb" again.
Example 2
sheet = Spreadsheet(["q1", "q2"])
history = History(max_commands=10)
exported = []
history.run(BatchCommand([
SetCellCommand(sheet, "q1", "rev", 25),
SetCellCommand(sheet, "q2", "rev", 35),
]))
history.run(SetCellCommand(sheet, "q2", "sum", Formula([("q1", "rev"), ("q2", "rev")])))
sheet.get("q2", "sum") # -> 60
# Setting q1.rev = Formula([("q2", "sum")]) raises ValueError (cycle) and leaves q1.rev == 25.
history.undo() # -> True (reverts q2.sum back to empty -> 0)
history.run(PublishCommand(sheet, exported))
exported # -> [{("q1", "rev"): 25, ("q2", "rev"): 35}]
history.redo() # -> True (redo stack survived PublishCommand!)
sheet.get("q2", "sum") # -> 60
Walk-through: The two revenue writes execute as a single BatchCommand. After undoing the sum formula, PublishCommand exports the live cell values without mutating the sheet, so redo() remains available and restores ("q2", "sum") to 60.
Constraints
- A
Spreadsheetmay hold up to10^5cells across live rows; recalculation must visit only cells reachable downstream of the modified keys rather than scanning the entire sheet, and per-command state mementos must store deltas rather than full-sheet copies. 0 <= max_commands <= 10^4; evicted commands must be released from the undo buffer so memory stays bounded.- Formula dependency graphs must remain acyclic at all times; diamond dependencies (
dreadingbandc, which both reada) must evaluate each affected formula after all of its changing inputs have updated.
Step-by-step walkthrough
Understand the problem and choose stable row IDs
Undo and redo in a spreadsheet are harder than in a plain text box for three reasons: changing one cell cascades into formulas that read it, deleting a row breaks formulas and shifts rows underneath it, and external actions like publishing cannot be taken back.
To keep these concerns cleanly separated, we use the Command pattern — a design pattern that wraps each user action into an object with
execute()andundo()methods instead of mutating data directly from the UI. That gives us three clean roles:Spreadsheet (the receiver: owns the data, cached values, and dependency graph) Command (one user action: execute(), undo(), undoable, invalidates_history) +-- SetCellCommand writes a number, Formula, or None to one cell +-- DeleteRowCommand removes one row and restores it at the same index +-- BatchCommand runs and undoes several commands as one atomic step +-- PublishCommand sends a snapshot outside the app (not undoable) History (the invoker: runs commands and manages bounded undo/redo stacks)One data-modeling choice makes row deletion dramatically simpler: give every row a stable string ID (such as
"feb"), and store the visual top-to-bottom order separately in a listself.rows. Look at what happens when row 2 is deleted under positional numbers versus stable IDs:Positional references (fragile): Row 2 holds 10; Row 3 has formula "=A2 + 1" Delete Row 2 -> Row 3 slides up to Row 2; every formula below Row 2 must be rewritten! Stable row IDs (clean): rows = ["r1", "r2", "r3"]; cell ("r3", "a") holds Formula([("r2", "a")]) Delete "r2" -> rows = ["r1", "r3"]; ("r3", "a") still references ("r2", "a") -> #REF! Undo -> rows = ["r1", "r2", "r3"]; ("r2", "a") exists again -> value restored!Because formulas point to
("r2", "a")rather than "the second row", deleting or restoring a row never forces us to rewrite formulas in other rows.Why whole-sheet snapshots fail at 100,000 cells
The most obvious undo strategy saves a full deep copy of the spreadsheet before every command and swaps that copy back on
undo(). That brute-force strategy is great as a test oracle, andtests.pyuses it to verify our engine on random action sequences.In production, whole-sheet snapshots fail both memory and speed requirements. On a 100,000-cell sheet with a 100-step undo history, storing 100 full copies keeps up to
100 * 100,000 = 10,000,000cell entries in RAM — even if the user just typed single numbers into 100 cells. Restoring a snapshot also takes work proportional to the entire sheet rather than the single cell that changed.Instead, each command stores a memento — a tiny saved record of only the state that specific command overwrote:
Command Memento saved right before execute() Memory cost SetCellCommand previous content of that 1 cell O(1) DeleteRowCommand old display index + that row's cells O(non-empty cells in row) BatchCommand list of child Command objects sum of childrenFor this to be safe, cell contents (
int,float,None, andFormula) must be treated as immutable (never modified in place after creation), so holding a reference to the oldFormulainself.beforepreserves it faithfully.Track formula dependencies with a reverse graph
Undo is just another state change, so undoing an edit must recalculate downstream formulas the exact same way a forward edit does. To know which formulas care when cell
Xchanges without scanning all 100,000 cells, theSpreadsheetmaintains a reverse dependency graph — a dictionarydependents[input_cell]mapping each cell to the set of formula cells that read it.Whenever a formula is written or removed,
_linkand_unlinkupdate those sets. Before allowing a new formula atkey,creates_cyclewalks forward alongdependentsstarting fromkeyto find every cell downstream ofkey. If the new formula tries to read any cell already in thatdownstreamset (includingkeyitself), writing it would create an infinite loop:Existing graph: ("r1", "b") --reads--> ("r1", "a") dependents[("r1", "b")] = {("r1", "a")} Attempt: set ("r1", "b") = Formula([("r1", "a")]) 1. Walk dependents from ("r1", "b") -> downstream = {("r1", "b"), ("r1", "a")} 2. New formula wants to read ("r1", "a"), which is in downstream -> CYCLE! Reject.def _link(self, key: CellKey, content) -> None: """Register `key` as a reader of every cell referenced by `content`.""" if isinstance(content, Formula): for ref in content.refs: if ref not in self.dependents: self.dependents[ref] = set() self.dependents[ref].add(key) def _unlink(self, key: CellKey, content) -> None: """Remove `key` from the reader sets of every cell referenced by `content`.""" if isinstance(content, Formula): for ref in content.refs: users = self.dependents.get(ref) if users is not None: users.discard(key) # Clean up empty sets so `dependents` stays proportional to active references if not users: del self.dependents[ref] def creates_cycle(self, key: CellKey, content) -> bool: """Return True if writing `content` at `key` would make `key` depend on itself.""" if not isinstance(content, Formula): return False # Walk forward from `key` to collect every cell that directly or indirectly reads `key`. # Including `key` itself catches direct self-references such as c = Formula([c]). downstream = {key} stack = [key] while stack: cell = stack.pop() for user in self.dependents.get(cell, ()): if user not in downstream: downstream.add(user) stack.append(user) # If the new formula reads any cell already downstream of `key`, adding it closes a loop for ref in content.refs: if ref in downstream: return True return FalseRecalculate affected cells in topological order
Suppose cell
afeeds bothb = aandc = a + a, andd = b + creads both:+---> b --->+ a ---+ +---> d = b + c +---> c --->+If we recomputed readers naively by recursion ("when
aupdates, immediately updateb, which immediately updatesd, then updatec, which updatesda second time"),dwould first be evaluated using the newband the stalec, and a chain ofkdiamonds would evaluate the last cell2^ktimes!Instead, we recompute affected cells in topological order — a sequence where every formula is evaluated only after all of its changing inputs have finished updating. We compute this order on just the affected subgraph using Kahn's algorithm (tracking how many changing inputs each cell is still waiting for, and processing cells whose wait count hits zero):
- Collect
affected: traversedependentsfromchangedto gather only cells reachable from this edit. Unrelated cells in the 100,000-cell sheet are never touched. - Count
waiting: for each edgekey -> userinsideaffected, incrementwaiting[user]. Inputs outsideaffecteddid not change, so their cached values inself.valuesare already final and we do not wait on them. - Process
ready: start with cells inaffectedthat havewaiting == 0, refresh each one's value, and decrementwaitingon its readers. When a reader's count reaches0, push it toready.
def recalculate(self, changed) -> None: """Recompute `changed` cells and everything downstream of them in topological order.""" # Phase 1: Graph traversal to collect only the subgraph reachable from `changed` affected: Set[CellKey] = set() stack = list(changed) while stack: key = stack.pop() if key in affected: continue affected.add(key) for user in self.dependents.get(key, ()): stack.append(user) # Phase 2: Count how many inputs INSIDE `affected` each cell must wait for. # Inputs outside `affected` did not change, so their cached values are already final. waiting: Dict[CellKey, int] = {} for key in affected: waiting[key] = 0 for key in affected: for user in self.dependents.get(key, ()): waiting[user] += 1 # Phase 3: Kahn's topological sort — refresh a cell only after all changing inputs finish ready = [] for key in affected: if waiting[key] == 0: ready.append(key) while ready: key = ready.pop() self._refresh(key) for user in self.dependents.get(key, ()): waiting[user] -= 1 if waiting[user] == 0: ready.append(user)Because
creates_cycleblocks cycles at write time, every cell inaffectedis guaranteed to reachwaiting == 0and refresh once.- Collect
Implement cell edits with validate-save-mutate
Every undoable command follows a strict three-step sequence inside
execute():- Validate first: check that the row exists and the formula creates no cycle. Raising
ValueErrorbefore touching anything means a failed command requires zero cleanup and is never added to history. - Save the memento (
self.before): read the cell's current content at execution time (not inside__init__, when the command object was merely constructed). - Mutate via the receiver: call
sheet.write_cell(...), which unlinks old edges, stores the new content, links new edges, and triggersrecalculate.
Because undo and redo operate in LIFO (last-in, first-out) order, calling
redo()always finds the sheet in the exact stateexecute()saw originally, soredo()can simply callcommand.execute()again.class SetCellCommand(Command): """Set one cell to a number, a Formula, or None (clear).""" def __init__(self, sheet: Spreadsheet, row_id: str, col: str, content): self.sheet = sheet self.row_id = row_id self.col = col self.after = content self.before = None # memento captured right before mutation in execute() def execute(self) -> None: # Validate before mutating so a rejected command leaves the sheet untouched if not self.sheet.has_row(self.row_id): raise ValueError(f"row {self.row_id!r} does not exist") if self.sheet.creates_cycle((self.row_id, self.col), self.after): raise ValueError("formula would create a circular reference") self.before = self.sheet.content(self.row_id, self.col) self.sheet.write_cell(self.row_id, self.col, self.after) def undo(self) -> None: self.sheet.write_cell(self.row_id, self.col, self.before)- Validate first: check that the row exists and the formula creates no cycle. Raising
Handle row deletion and restoration cleanly
Deleting a row
row_idinteracts with two distinct groups of formulas:- External formulas that read
row_id: their formula objects do not change, and their edges inself.dependentsstay right where they are. Whenrow_idis removed fromself.cells,get(row_id, col)returns"#REF!", so recalculating turns every reader (and anything downstream of it) into"#REF!". Notice a subtle trap: what if a formula in"jan"reads an empty cell("feb", "z")? Before deleting"feb", that formula evaluated to0; after deleting"feb", it must become"#REF!"! That is why_keys_in_rowcollects both non-empty cells ofrow_idand any cell ofrow_idpresent inself.dependents. - Formulas living inside
row_id: these disappear along with the row, so we must call_unlinkon them duringremove_row. Otherwise a deleted formula would stay registered independentsand could falsely triggercreates_cycleon future edits!
On
undo(),insert_rowputsrow_idback at its savedindex, restores its cell dictionary, re-links its own formulas, and recalculates_keys_in_row(row_id)so external#REF!cells recover their numbers automatically.def _keys_in_row(self, row_id: str) -> Set[CellKey]: """Collect every cell in `row_id` that is non-empty OR read by an external formula.""" keys: Set[CellKey] = set() for col in self.cells.get(row_id, {}): keys.add((row_id, col)) # Also include empty cells in `row_id` that some formula reads, so they flip 0 <-> #REF! for referenced_key in self.dependents: if referenced_key[0] == row_id: keys.add(referenced_key) return keys def remove_row(self, row_id: str) -> Tuple[int, Dict[str, object]]: """Delete a row and return (old_index, saved_cells) so undo can restore it.""" keys = self._keys_in_row(row_id) index = self.rows.index(row_id) saved = self.cells.pop(row_id) self.rows.pop(index) # Unlink formulas that lived inside the deleted row so they stop listening to inputs for col, content in saved.items(): self._unlink((row_id, col), content) # Refresh removed cells (clearing `values`) and turn downstream formulas into #REF! self.recalculate(keys) return index, saved def insert_row(self, row_id: str, index: int, saved: Dict[str, object]) -> None: """Re-insert a deleted row at its old position and re-register its own formulas.""" self.rows.insert(index, row_id) self.cells[row_id] = dict(saved) for col, content in saved.items(): self._link((row_id, col), content) self.recalculate(self._keys_in_row(row_id))- External formulas that read
Add batch commands, non-undoable actions, and bounded history
Three remaining pieces complete the architecture:
BatchCommand(transactional groups): runs child commands in forward order and records each completed child indone. If childkraisesValueError, it callsundo()onreversed(done)before re-raising so a failed batch leaves zero partial changes.BatchCommand.undo()also iterates inreversed(self.commands)— if a batch sets cellato7and then to8, undoing8 -> 7first and7 -> oldsecond restoresold, whereas forward order would leave7!- Non-undoable commands (
undoable = False):PublishCommandexportssheet.snapshot()to an external list without modifying the sheet, soHistory.runneither records it nor touches the stacks. By contrast, a non-undoable command that replaces sheet data wholesale setsinvalidates_history = True, instructingHistoryto clear both stacks because older mementos no longer match the sheet. - Bounded
History:self.undo_stack = deque(maxlen=max_commands)automatically evicts the oldest command in O(1) time once full, preventing memory leaks. Any fresh undoable command clearsself.redo_stackbecause the timeline has branched:
run(A), run(B), run(C): undo_stack = [A, B, C] redo_stack = [] undo(): undo_stack = [A, B] redo_stack = [C] run(D) (new branch!): undo_stack = [A, B, D] redo_stack = [] (C discarded)class History: """Executes commands while maintaining a bounded undo stack and a redo stack.""" def __init__(self, max_commands: int = 100): if max_commands < 0: raise ValueError("max_commands must be >= 0") # undo_stack: bounded deque of Command; automatically evicts the oldest entry when full self.undo_stack = deque(maxlen=max_commands) # redo_stack: LIFO list of undone Command objects; cleared on any new undoable edit self.redo_stack: List[Command] = [] def run(self, command: Command) -> None: # If execute() raises ValueError, we exit before touching either history stack command.execute() if not command.undoable: if command.invalidates_history: self.undo_stack.clear() self.redo_stack.clear() return self.undo_stack.append(command) self.redo_stack.clear() def undo(self) -> bool: if not self.undo_stack: return False command = self.undo_stack.pop() command.undo() self.redo_stack.append(command) return True def redo(self) -> bool: if not self.redo_stack: return False command = self.redo_stack.pop() command.execute() self.undo_stack.append(command) return TrueTrace Sample 1 and assemble the full solution
Let's trace
Example 1onrows = ["hdr", "jan", "feb", "tot"]with("jan", "price") = 40,("feb", "price") = 60, and("tot", "price") = Formula([("jan", "price"), ("feb", "price")]):Initial state: rows = ["hdr", "jan", "feb", "tot"] values: ("jan", "price") = 40, ("feb", "price") = 60, ("tot", "price") = 100 dependents: ("jan", "price") -> {("tot", "price")}, ("feb", "price") -> {("tot", "price")} 1. history.run(DeleteRowCommand(sheet, "feb")): - Memento saved: index = 2, saved = {"price": 60} - rows = ["hdr", "jan", "tot"]; "feb" popped from cells - recalculate({("feb", "price")}) visits ("feb", "price") -> ("tot", "price") in topological order: ("feb", "price") removed from values, ("tot", "price") = "#REF!" 2. history.undo(): - insert_row("feb", 2, {"price": 60}) restores rows = ["hdr", "jan", "feb", "tot"] - Edge ("feb", "price") -> {("tot", "price")} is still intact! - recalculate({("feb", "price")}) restores ("feb", "price") = 60 -> ("tot", "price") = 100 3. history.redo(): - Re-runs DeleteRowCommand.execute(): rows = ["hdr", "jan", "tot"], ("tot", "price") = "#REF!"Here is the complete, self-contained implementation:
from typing import Dict, List, Optional, Set, Tuple from collections import deque CellKey = Tuple[str, str] # (row_id, column), e.g. ("r5", "a") REF_ERROR = "#REF!" class Formula: """A formula cell whose value is the sum of its referenced cells. Treated as immutable.""" def __init__(self, refs: List[CellKey]): # Copy the list so external callers cannot mutate a stored formula in place self.refs = list(refs) def __repr__(self): return f"Formula({self.refs!r})" class Spreadsheet: """The receiver: holds raw cell contents, cached values, and the reverse dependency graph. Rows have stable string IDs (like "r5"), while `rows` stores their current display order. Because formulas reference stable row IDs instead of numeric positions, deleting a row never forces us to rewrite formulas in the rows below it. """ def __init__(self, row_ids: List[str]): # rows: display order of live row IDs, e.g. ["r1", "r2", "r5"] self.rows = list(row_ids) # cells: {row_id: {col: number_or_Formula}}, e.g. {"r1": {"a": 3, "b": Formula(...)}} self.cells: Dict[str, Dict[str, object]] = {} for row_id in self.rows: self.cells[row_id] = {} # values: cached evaluated value per non-empty live cell, e.g. {("r1", "a"): 3} self.values: Dict[CellKey, object] = {} # dependents: reverse dependency graph {input_cell: {formula_cells_that_read_it}}. # Edges from a deleted row to live formulas are kept so undo restores them automatically. self.dependents: Dict[CellKey, Set[CellKey]] = {} # ----- reading ----- def has_row(self, row_id: str) -> bool: return row_id in self.cells def get(self, row_id: str, col: str): """Computed value: a number, 0 for an empty cell, or '#REF!' if the row is deleted.""" if row_id not in self.cells: return REF_ERROR return self.values.get((row_id, col), 0) def content(self, row_id: str, col: str): """Raw user content: a number, a Formula, or None for an empty cell.""" return self.cells[row_id].get(col) def snapshot(self) -> Dict[CellKey, object]: """Values of every non-empty cell in a live row.""" return dict(self.values) # ----- dependency graph ----- def _link(self, key: CellKey, content) -> None: """Register `key` as a reader of every cell referenced by `content`.""" if isinstance(content, Formula): for ref in content.refs: if ref not in self.dependents: self.dependents[ref] = set() self.dependents[ref].add(key) def _unlink(self, key: CellKey, content) -> None: """Remove `key` from the reader sets of every cell referenced by `content`.""" if isinstance(content, Formula): for ref in content.refs: users = self.dependents.get(ref) if users is not None: users.discard(key) # Clean up empty sets so `dependents` stays proportional to active references if not users: del self.dependents[ref] def creates_cycle(self, key: CellKey, content) -> bool: """Return True if writing `content` at `key` would make `key` depend on itself.""" if not isinstance(content, Formula): return False # Walk forward from `key` to collect every cell that directly or indirectly reads `key`. # Including `key` itself catches direct self-references such as c = Formula([c]). downstream = {key} stack = [key] while stack: cell = stack.pop() for user in self.dependents.get(cell, ()): if user not in downstream: downstream.add(user) stack.append(user) # If the new formula reads any cell already downstream of `key`, adding it closes a loop for ref in content.refs: if ref in downstream: return True return False # ----- recalculation ----- def _evaluate(self, formula: Formula): """Sum all referenced cells; propagate '#REF!' if any referenced row is deleted.""" total = 0 for ref_row, ref_col in formula.refs: value = self.get(ref_row, ref_col) if value == REF_ERROR: return REF_ERROR total += value return total def _refresh(self, key: CellKey) -> None: """Recompute the cached value of a single cell from its current raw content.""" row_id, col = key row = self.cells.get(row_id) # If the row was deleted or the cell was cleared, remove any cached value if row is None: content = None else: content = row.get(col) if content is None: self.values.pop(key, None) elif isinstance(content, Formula): self.values[key] = self._evaluate(content) else: self.values[key] = content def recalculate(self, changed) -> None: """Recompute `changed` cells and everything downstream of them in topological order.""" # Phase 1: Graph traversal to collect only the subgraph reachable from `changed` affected: Set[CellKey] = set() stack = list(changed) while stack: key = stack.pop() if key in affected: continue affected.add(key) for user in self.dependents.get(key, ()): stack.append(user) # Phase 2: Count how many inputs INSIDE `affected` each cell must wait for. # Inputs outside `affected` did not change, so their cached values are already final. waiting: Dict[CellKey, int] = {} for key in affected: waiting[key] = 0 for key in affected: for user in self.dependents.get(key, ()): waiting[user] += 1 # Phase 3: Kahn's topological sort — refresh a cell only after all changing inputs finish ready = [] for key in affected: if waiting[key] == 0: ready.append(key) while ready: key = ready.pop() self._refresh(key) for user in self.dependents.get(key, ()): waiting[user] -= 1 if waiting[user] == 0: ready.append(user) # ----- mutations used by commands ----- def write_cell(self, row_id: str, col: str, content) -> None: """Store `content` (None clears the cell), update dependency edges, and recalculate.""" key = (row_id, col) row = self.cells[row_id] # Unlink old formula edges before overwriting the cell self._unlink(key, row.get(col)) if content is None: row.pop(col, None) else: row[col] = content self._link(key, content) self.recalculate([key]) def _keys_in_row(self, row_id: str) -> Set[CellKey]: """Collect every cell in `row_id` that is non-empty OR read by an external formula.""" keys: Set[CellKey] = set() for col in self.cells.get(row_id, {}): keys.add((row_id, col)) # Also include empty cells in `row_id` that some formula reads, so they flip 0 <-> #REF! for referenced_key in self.dependents: if referenced_key[0] == row_id: keys.add(referenced_key) return keys def remove_row(self, row_id: str) -> Tuple[int, Dict[str, object]]: """Delete a row and return (old_index, saved_cells) so undo can restore it.""" keys = self._keys_in_row(row_id) index = self.rows.index(row_id) saved = self.cells.pop(row_id) self.rows.pop(index) # Unlink formulas that lived inside the deleted row so they stop listening to inputs for col, content in saved.items(): self._unlink((row_id, col), content) # Refresh removed cells (clearing `values`) and turn downstream formulas into #REF! self.recalculate(keys) return index, saved def insert_row(self, row_id: str, index: int, saved: Dict[str, object]) -> None: """Re-insert a deleted row at its old position and re-register its own formulas.""" self.rows.insert(index, row_id) self.cells[row_id] = dict(saved) for col, content in saved.items(): self._link((row_id, col), content) self.recalculate(self._keys_in_row(row_id)) class Command: """One user action. After undo() the sheet must be exactly as it was before execute().""" undoable = True invalidates_history = False # True for non-undoable actions that alter sheet state def execute(self) -> None: raise NotImplementedError def undo(self) -> None: raise NotImplementedError class SetCellCommand(Command): """Set one cell to a number, a Formula, or None (clear).""" def __init__(self, sheet: Spreadsheet, row_id: str, col: str, content): self.sheet = sheet self.row_id = row_id self.col = col self.after = content self.before = None # memento captured right before mutation in execute() def execute(self) -> None: # Validate before mutating so a rejected command leaves the sheet untouched if not self.sheet.has_row(self.row_id): raise ValueError(f"row {self.row_id!r} does not exist") if self.sheet.creates_cycle((self.row_id, self.col), self.after): raise ValueError("formula would create a circular reference") self.before = self.sheet.content(self.row_id, self.col) self.sheet.write_cell(self.row_id, self.col, self.after) def undo(self) -> None: self.sheet.write_cell(self.row_id, self.col, self.before) class DeleteRowCommand(Command): """Delete a row, saving its display index and cell contents as a memento for undo.""" def __init__(self, sheet: Spreadsheet, row_id: str): self.sheet = sheet self.row_id = row_id self.index: Optional[int] = None self.saved: Optional[Dict[str, object]] = None def execute(self) -> None: if not self.sheet.has_row(self.row_id): raise ValueError(f"row {self.row_id!r} does not exist") self.index, self.saved = self.sheet.remove_row(self.row_id) def undo(self) -> None: self.sheet.insert_row(self.row_id, self.index, self.saved) class BatchCommand(Command): """Several undoable commands executed and undone together as a single atomic step.""" def __init__(self, commands: List[Command]): for command in commands: if not command.undoable: raise ValueError("a batch may only contain undoable commands") self.commands = list(commands) def execute(self) -> None: done: List[Command] = [] try: for command in self.commands: command.execute() done.append(command) except ValueError: # Roll back already-applied children in reverse (LIFO) order so nothing sticks for command in reversed(done): command.undo() raise def undo(self) -> None: # Reverse order matters when two children in the batch touch the same cell or row for command in reversed(self.commands): command.undo() class PublishCommand(Command): """Export a value snapshot externally. Non-undoable, and does not alter local sheet state.""" undoable = False def __init__(self, sheet: Spreadsheet, destination: list): self.sheet = sheet self.destination = destination def execute(self) -> None: self.destination.append(self.sheet.snapshot()) def undo(self) -> None: raise RuntimeError("publishing cannot be undone") class History: """Executes commands while maintaining a bounded undo stack and a redo stack.""" def __init__(self, max_commands: int = 100): if max_commands < 0: raise ValueError("max_commands must be >= 0") # undo_stack: bounded deque of Command; automatically evicts the oldest entry when full self.undo_stack = deque(maxlen=max_commands) # redo_stack: LIFO list of undone Command objects; cleared on any new undoable edit self.redo_stack: List[Command] = [] def run(self, command: Command) -> None: # If execute() raises ValueError, we exit before touching either history stack command.execute() if not command.undoable: if command.invalidates_history: self.undo_stack.clear() self.redo_stack.clear() return self.undo_stack.append(command) self.redo_stack.clear() def can_undo(self) -> bool: return len(self.undo_stack) > 0 def can_redo(self) -> bool: return len(self.redo_stack) > 0 def undo(self) -> bool: if not self.undo_stack: return False command = self.undo_stack.pop() command.undo() self.redo_stack.append(command) return True def redo(self) -> bool: if not self.redo_stack: return False command = self.redo_stack.pop() command.execute() self.undo_stack.append(command) return True✅ Submit now — all tests should pass.
Intuition & how it works
Think of undo and redo like keeping a stack of tiny sticky notes on a ledger, paired with a wiring board connecting formulas to their inputs. Instead of photocopying the entire 100,000-cell ledger before every edit, each action (wrapped in the Command pattern, where every edit is an object with execute() and undo() methods) writes down only a memento — the tiny piece of state it is about to overwrite, such as "cell jan.price used to hold 40" or "row feb used to sit at index 2 with {"price": 60}." Meanwhile, the spreadsheet gives every row a permanent ID (like "feb") separate from its visual row number, and maintains a reverse dependency graph (a lookup table mapping each cell to the formulas that read it).
Copying the whole spreadsheet before each of 100 edits would store up to 10 million cell entries in memory and force slow whole-sheet restores for a single-cell change. Likewise, referencing rows by visual row number (A3) means deleting row 3 shifts every row below it and forces rewriting every formula underneath. Finally, recomputing formulas naively by immediate recursion can evaluate shared downstream cells exponentially many times when dependencies form diamond shapes, so we instead recompute affected cells in topological order (an order where every formula runs once, strictly after all of its changing inputs have updated).
Walk through Example 1 on rows = ["hdr", "jan", "feb", "tot"] with jan.price = 40, feb.price = 60, and tot.price = Formula([("jan", "price"), ("feb", "price")]), which evaluates to 100:
1. Delete row "feb": DeleteRowCommand saves (index=2, saved={"price": 60}), removes "feb", and triggers recalculation on ("feb", "price") and its reader ("tot", "price"). Because "feb" is gone, ("tot", "price") becomes "#REF!", while its dependency edge from ("feb", "price") stays registered.
2. Undo: DeleteRowCommand.undo() re-inserts "feb" at index 2 with {"price": 60} and recalculates ("feb", "price") (60) followed by ("tot", "price") (40 + 60 = 100).
3. Redo: History.redo() pops the command from the redo stack and calls execute() again, returning ("tot", "price") to "#REF!".
Complexity
Let A be the number of cells downstream of a change (including the changed cells themselves), E_A be the number of dependency edges among those affected cells, F be the total number of cell references summed across affected formulas, R be the number of live rows, and D be the number of distinct cells currently referenced by at least one formula.
SetCellCommand.executeandundo:O(A + E_A + F + r)time, whereris the number of references in the overwritten formula. Unlinking the old formula touchesrentries independents,creates_cyclewalks the downstream subgraph once inO(A + E_A), andrecalculateruns Kahn's algorithm (an in-degree counting pass that processes nodes only when all predecessors are done) inO(A + E_A)plusO(F)to sum the affected formulas' inputs. Unrelated cells among the 100,000 cells in the sheet are never visited.DeleteRowCommand.executeandundo:O(R + D + c + A + E_A + F)time, wherecis the number of non-empty cells in the deleted row. Finding and removing or inserting the row ID in Python'srowslist shifts up toRpointers, unlinking or re-linking the row's own cells takesO(c)plus their formula references,_keys_in_rowscans theDreferenced keys independents, andrecalculateupdates the affected subgraph inO(A + E_A + F). (If row deletions were frequent, maintaining a secondaryrow_id -> referenced_colsdict would drop theO(D)scan toO(1).)History.run,undo, andredo:O(1)amortized bookkeeping on top of the command's own cost. Appending and popping on adeque(maxlen=max_commands)or Python list isO(1), and clearingredo_stackon a new edit only discards items pushed by earlierundo()calls, so each item is pushed and popped at most once.- Space:
O(N + D + E)for the sheet (withNnon-empty cells andEtotal formula references), plusO(max_commands)command mementos in history. Becausedeque(maxlen=max_commands)drops the oldest command automatically and each memento stores only a delta (O(1)per cell edit,O(c)per deleted row), history memory stays strictly bounded.
Edge cases
- Formulas reading an empty cell in a deleted row: Before deletion, an empty cell evaluates to
0; after its row is deleted, any formula referencing it must become"#REF!". That is why_keys_in_rowcollects referenced cells inself.dependentsin addition to non-empty cells inself.cells[row_id]. - Direct self-reference (
c = Formula([c])) and multi-hop cycles (a -> b -> a): Initializingdownstream = {key}increates_cyclecatches length-1 self-loops and longer cycles with the exact same check, raisingValueErrorbefore any state changes. - Formulas inside a deleted row: When a row is deleted, its own formulas must be unlinked from
dependents. Otherwise they remain phantom listeners that could falsely triggercreates_cyclewhen editing their former inputs. - Failing child inside a
BatchCommand: If the third command of a five-command batch raisesValueError, the first two commands are undone in reverse order and neither stack inHistoryis modified. - Editing the same cell twice in one
BatchCommand: BecauseBatchCommand.undo()runs children inreversed(...)order,a: None -> 7followed bya: 7 -> 8undoes8 -> 7first and7 -> Nonesecond, restoringNonecleanly. max_commands = 0:deque(maxlen=0)immediately discards pushed commands, so edits still execute normally whileundo()cleanly returnsFalse.- Non-undoable actions (
PublishCommandvsinvalidates_history): Exporting a snapshot does not modify the sheet, so prior local edits and pending redos remain valid. A non-undoable bulk import that overwrites the sheet setsinvalidates_history = Trueso both stacks clear safely.
Common mistakes
- Saving full-sheet copies per edit: Easy to write, but 100 snapshots of 100,000 cells consumes 10 million cell entries and makes every undo
O(N). - Capturing
beforein__init__instead ofexecute(): In aBatchCommand(such as two edits to the same cell) or duringredo(), the sheet state right beforeexecute()can differ from when the command object was constructed. - Mutating
Formulaobjects in place: If a caller modifiesformula.refsafter passing it in, any memento pointing to thatFormulasilently changes too. Copyinglist(refs)and treating cell contents as immutable avoids this bug. - Recursive push recalculation without topological sorting: Updating readers immediately in DFS/BFS discovery order produces transient wrong intermediate values and can take
O(2^k)work on chained diamond dependencies. - Forgetting to clear
redo_stackon a new undoable edit: Leaving old redo commands around lets a user re-apply an old command onto a completely new timeline whosebeforestate no longer matches. - Validating halfway through
execute(): Mutatingcellsbefore checkingcreates_cycleleaves the spreadsheet half-updated when an exception is raised.
Follow-up questions
- How should multi-cell actions—such as pasting a block or dragging autofill across dozens of cells—be grouped and recalculated? Wrap all child
SetCellCommandinstances inside a singleBatchCommandso one Undo reverts the entire gesture atomically, rolling back already-applied children in reverse order if any child fails validation. In our clean baseline implementation, each child callswrite_celland recalculates immediately; for large pastes or autofill gestures where dozens of cells feed the same summary formulas, you can add a deferred-recalculation batch mode onSpreadsheetthat applies all raw writes first and callsrecalculate(all_changed_keys)once at the end so shared dependents evaluate once instead of dozens of times. For rapid keystrokes in a single cell, UIs also use coalescing (merging consecutive edits to the same cell within a short time window like 500 ms into one command) so Undo steps back by whole thoughts rather than single characters. - How should the interface warn users before irreversible actions, and when should those actions wipe versus preserve existing undo stacks? Before executing, show a confirmation dialog stating clearly that the action cannot be undone (for example, "Exporting sends a live snapshot to viewers and cannot be undone"). How history is handled depends on whether the action mutates the local sheet: an external side effect like
PublishCommandleaves the sheet untouched, so we neither record it nor clearundo_stack/redo_stack, keeping the Undo button labeled with the user's previous cell edit. By contrast, a non-undoable action that mutates the sheet outside memento tracking (such as replacing the sheet from an external CSV) setsinvalidates_history = True, clears both stacks so stale mementos cannot corrupt the new data, and warns in the confirmation dialog that undo history will be reset. - How would you store and synchronize command logs on a backend service so multiple collaborators can edit and undo concurrently? Serialize each command as a JSON operation (
type,row_id,col,before,after,user_id,base_version) and append it to an ordered operation log on the server, which broadcasts accepted operations to connected clients. In multiplayer editing, User A's Undo cannot blindly rewind global state without erasing User B's newer edits; instead, Undo generates a new forward inverse operation applied to the current sheet, and each user's local undo stack tracks only their own actions. If User B has since overwritten the same cell (current != command.before), the system resolves the conflict via operational transformation (mathematically adjusting concurrent operations so they commute) or rejects/prompts before overwriting User B's newer value. Using stable UUID row IDs is essential here so concurrent row inserts and deletes never shift each other's coordinates.
Alternative approaches
- Inverse commands instead of mementos: At
execute()time, each command constructs its explicit inverse command object (for example,DeleteRowCommandcreates anInsertRowCommand). This is equivalent in memory to mementos and maps directly onto serialized operation logs for multiplayer backends. - Persistent (immutable) data structures: A persistent data structure preserves previous versions of itself when modified by sharing unchanged tree nodes (structural sharing, e.g. hash-array mapped tries), making
Spreadsheetsnapshots costO(log N)space per edit andO(1)time to undo. However, it carries higher constant-factor overhead in Python and still requires explicit handling for non-undoable external side effects. - Event sourcing with periodic checkpoints: Event sourcing stores only the append-only log of commands plus an occasional full checkpoint (say every 500 commands), reconstructing earlier states by replaying from the nearest checkpoint. This gives full audit history and arbitrary time-travel at the cost of slower undo latency when replaying hundreds of steps.
Follow-up questions
- How should multi-cell actions—such as pasting a block or dragging autofill across dozens of cells—be grouped and recalculated?
- How should the interface warn users before irreversible actions, and when should those actions wipe versus preserve existing undo stacks?
- How would you store and synchronize command logs on a backend service so multiple collaborators can edit and undo concurrently?
Similar questions
- Resilient HTTP Client with Retries and Idempotency
- Reusable Database Connection Pool
- Fast Best-Fit Dispatcher for Memory-Bound Workloads
- Calculate Working Days Between Dates
- Thread-Safe On-Demand Connection Pool
- Sharded Multi-Tenant Full-Text Search Service
More Airtable interview questions
- Fast Best-Fit Dispatcher for Memory-Bound Workloads Easy
- Calculate Working Days Between Dates Medium
- Deterministic JSON Wire Format for Cyclic Graphs Hard Pro
- Schema-Grounded Formula Assistant for Collaborative Tables Medium Pro
- Thread-Safe On-Demand Connection Pool Medium Pro
- Sharded Multi-Tenant Full-Text Search Service Medium Pro
- Idempotent Asynchronous Job Execution API Medium Pro
- Workspace Metric Drop Triage and Recommendation Experiment Easy Pro
- Resilient HTTP Client with Retries and Idempotency Medium Pro
- Breadth-First Object Graph Serialization Medium Pro