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 to 0).
    • If any referenced cell belongs to a deleted row—or itself evaluates to "#REF!"—the formula evaluates to "#REF!".
  • Spreadsheet(row_ids: List[str])
    • Stores self.rows as the current top-to-bottom display list of live row_id strings.
    • has_row(row_id: str) -> bool: returns True if row_id is currently live, else False.
    • get(row_id: str, col: str): returns "#REF!" when row_id has been deleted, 0 when (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.

Commands & Bounded History

  • Command
    • Base class defining class flags undoable = True and invalidates_history = False, along with execute() -> None and undo() -> None.
  • SetCellCommand(sheet: Spreadsheet, row_id: str, col: str, content)
    • Writes a numeric value (int or float), a Formula, or None (clearing the cell) to (row_id, col) and recalculates downstream dependents.
    • execute() must raise ValueError without modifying anything if row_id is not live or if content is a Formula that creates a self-reference or dependency cycle.
    • undo() restores the cell's prior raw content and recalculates downstream dependents.
  • DeleteRowCommand(sheet: Spreadsheet, row_id: str)
    • execute() raises ValueError if row_id is not live. Otherwise removes row_id from sheet.rows and cell storage, detaches any formulas that lived inside row_id so they no longer act as active listeners, and updates every external formula reading row_id (including empty cells in row_id) to "#REF!".
    • undo() re-inserts row_id at its former index in sheet.rows with all saved cells, reconnects its formulas, and recalculates downstream readers so "#REF!" values recover.
  • BatchCommand(commands: List[Command])
    • Raises ValueError at construction if any child has undoable == False.
    • execute() runs children in order; if a child raises ValueError, every previously executed child in the batch is undone in reverse order and ValueError is re-raised.
    • undo() reverts all children in reverse order as one step.
  • PublishCommand(sheet: Spreadsheet, destination: list)
    • Non-undoable external export (undoable = False, invalidates_history = False). execute() appends sheet.snapshot() to destination without changing sheet state; undo() raises RuntimeError.
  • History(max_commands: int = 100)
    • Raises ValueError if max_commands < 0.
    • run(command: Command) -> None: runs command.execute() (leaving both stacks untouched if ValueError is raised). If command.undoable is False, does not record the command—clearing both stacks when command.invalidates_history is True and preserving both stacks otherwise. If command.undoable is True, pushes onto a bounded undo buffer of capacity max_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 returns True (False when nothing can be undone).
    • redo() -> bool: re-executes the latest undone command, moves it back to the undo stack, and returns True (False when nothing can be redone).

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 Spreadsheet may hold up to 10^5 cells 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 (d reading b and c, which both read a) must evaluate each affected formula after all of its changing inputs have updated.

Step-by-step walkthrough

  1. 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() and undo() 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 list self.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.

  2. 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, and tests.py uses 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,000 cell 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 children
    

    For this to be safe, cell contents (int, float, None, and Formula) must be treated as immutable (never modified in place after creation), so holding a reference to the old Formula in self.before preserves it faithfully.

  3. 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 X changes without scanning all 100,000 cells, the Spreadsheet maintains a reverse dependency graph — a dictionary dependents[input_cell] mapping each cell to the set of formula cells that read it.

    Whenever a formula is written or removed, _link and _unlink update those sets. Before allowing a new formula at key, creates_cycle walks forward along dependents starting from key to find every cell downstream of key. If the new formula tries to read any cell already in that downstream set (including key itself), 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 False
    
  4. Recalculate affected cells in topological order

    Suppose cell a feeds both b = a and c = a + a, and d = b + c reads both:

            +---> b --->+
       a ---+           +---> d = b + c
            +---> c --->+
    

    If we recomputed readers naively by recursion ("when a updates, immediately update b, which immediately updates d, then update c, which updates d a second time"), d would first be evaluated using the new b and the stale c, and a chain of k diamonds would evaluate the last cell 2^k times!

    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):

    1. Collect affected: traverse dependents from changed to gather only cells reachable from this edit. Unrelated cells in the 100,000-cell sheet are never touched.
    2. Count waiting: for each edge key -> user inside affected, increment waiting[user]. Inputs outside affected did not change, so their cached values in self.values are already final and we do not wait on them.
    3. Process ready: start with cells in affected that have waiting == 0, refresh each one's value, and decrement waiting on its readers. When a reader's count reaches 0, push it to ready.
    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_cycle blocks cycles at write time, every cell in affected is guaranteed to reach waiting == 0 and refresh once.

  5. Implement cell edits with validate-save-mutate

    Every undoable command follows a strict three-step sequence inside execute():

    1. Validate first: check that the row exists and the formula creates no cycle. Raising ValueError before touching anything means a failed command requires zero cleanup and is never added to history.
    2. Save the memento (self.before): read the cell's current content at execution time (not inside __init__, when the command object was merely constructed).
    3. Mutate via the receiver: call sheet.write_cell(...), which unlinks old edges, stores the new content, links new edges, and triggers recalculate.

    Because undo and redo operate in LIFO (last-in, first-out) order, calling redo() always finds the sheet in the exact state execute() saw originally, so redo() can simply call command.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)
    
  6. Handle row deletion and restoration cleanly

    Deleting a row row_id interacts with two distinct groups of formulas:

    • External formulas that read row_id: their formula objects do not change, and their edges in self.dependents stay right where they are. When row_id is removed from self.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 to 0; after deleting "feb", it must become "#REF!"! That is why _keys_in_row collects both non-empty cells of row_id and any cell of row_id present in self.dependents.
    • Formulas living inside row_id: these disappear along with the row, so we must call _unlink on them during remove_row. Otherwise a deleted formula would stay registered in dependents and could falsely trigger creates_cycle on future edits!

    On undo(), insert_row puts row_id back at its saved index, 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))
    
  7. 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 in done. If child k raises ValueError, it calls undo() on reversed(done) before re-raising so a failed batch leaves zero partial changes. BatchCommand.undo() also iterates in reversed(self.commands) — if a batch sets cell a to 7 and then to 8, undoing 8 -> 7 first and 7 -> old second restores old, whereas forward order would leave 7!
    • Non-undoable commands (undoable = False): PublishCommand exports sheet.snapshot() to an external list without modifying the sheet, so History.run neither records it nor touches the stacks. By contrast, a non-undoable command that replaces sheet data wholesale sets invalidates_history = True, instructing History to 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 clears self.redo_stack because 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 True
    
  8. Trace Sample 1 and assemble the full solution

    Let's trace Example 1 on rows = ["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.execute and undo: O(A + E_A + F + r) time, where r is the number of references in the overwritten formula. Unlinking the old formula touches r entries in dependents, creates_cycle walks the downstream subgraph once in O(A + E_A), and recalculate runs Kahn's algorithm (an in-degree counting pass that processes nodes only when all predecessors are done) in O(A + E_A) plus O(F) to sum the affected formulas' inputs. Unrelated cells among the 100,000 cells in the sheet are never visited.
  • DeleteRowCommand.execute and undo: O(R + D + c + A + E_A + F) time, where c is the number of non-empty cells in the deleted row. Finding and removing or inserting the row ID in Python's rows list shifts up to R pointers, unlinking or re-linking the row's own cells takes O(c) plus their formula references, _keys_in_row scans the D referenced keys in dependents, and recalculate updates the affected subgraph in O(A + E_A + F). (If row deletions were frequent, maintaining a secondary row_id -> referenced_cols dict would drop the O(D) scan to O(1).)
  • History.run, undo, and redo: O(1) amortized bookkeeping on top of the command's own cost. Appending and popping on a deque(maxlen=max_commands) or Python list is O(1), and clearing redo_stack on a new edit only discards items pushed by earlier undo() calls, so each item is pushed and popped at most once.
  • Space: O(N + D + E) for the sheet (with N non-empty cells and E total formula references), plus O(max_commands) command mementos in history. Because deque(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_row collects referenced cells in self.dependents in addition to non-empty cells in self.cells[row_id].
  • Direct self-reference (c = Formula([c])) and multi-hop cycles (a -> b -> a): Initializing downstream = {key} in creates_cycle catches length-1 self-loops and longer cycles with the exact same check, raising ValueError before 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 trigger creates_cycle when editing their former inputs.
  • Failing child inside a BatchCommand: If the third command of a five-command batch raises ValueError, the first two commands are undone in reverse order and neither stack in History is modified.
  • Editing the same cell twice in one BatchCommand: Because BatchCommand.undo() runs children in reversed(...) order, a: None -> 7 followed by a: 7 -> 8 undoes 8 -> 7 first and 7 -> None second, restoring None cleanly.
  • max_commands = 0: deque(maxlen=0) immediately discards pushed commands, so edits still execute normally while undo() cleanly returns False.
  • Non-undoable actions (PublishCommand vs invalidates_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 sets invalidates_history = True so 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 before in __init__ instead of execute(): In a BatchCommand (such as two edits to the same cell) or during redo(), the sheet state right before execute() can differ from when the command object was constructed.
  • Mutating Formula objects in place: If a caller modifies formula.refs after passing it in, any memento pointing to that Formula silently changes too. Copying list(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_stack on a new undoable edit: Leaving old redo commands around lets a user re-apply an old command onto a completely new timeline whose before state no longer matches.
  • Validating halfway through execute(): Mutating cells before checking creates_cycle leaves 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 SetCellCommand instances inside a single BatchCommand so 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 calls write_cell and 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 on Spreadsheet that applies all raw writes first and calls recalculate(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 PublishCommand leaves the sheet untouched, so we neither record it nor clear undo_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) sets invalidates_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, DeleteRowCommand creates an InsertRowCommand). 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 Spreadsheet snapshots cost O(log N) space per edit and O(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

Similar questions

More Airtable interview questions

All 12 Airtable questions →