Reversible Edit History for a Formula-Driven Grid
Data Structure DesignModel answerLast updated
Design a command-based history for a spreadsheet that undoes and redoes cell edits, row deletions and batches, recomputes dependent formulas, handles irreversible actions, and bounds memory.
Reversible Edit History for a Formula-Driven Grid
You are building the editing core of a spreadsheet. Users type values and formulas into cells, and formulas can refer to other cells (for example, B2 holds =A1+B1). Users can also remove whole rows, which changes the meaning of formulas elsewhere in the sheet. Some actions reach outside the sheet entirely, such as publishing it to a public web address.
Design a history mechanism that lets users step backwards and forwards through their edits reliably.
What the design must cover
- Cell edits: changing the content of one cell.
- Row removal: deleting a row, including the effect on formulas that point into or below it.
- Recalculation: after any undo or redo, every affected formula must show a correct, up-to-date result.
- Irreversible actions: operations such as publishing that cannot be taken back.
Deliverables
- A
Commandabstraction exposingexecute()andundo(), plus any concrete command classes you need. - A description of what each command saves about the sheet before and after it runs, so rollbacks are exact.
- A description of how history is stored and how execution, undo and redo flow through it.
- Your strategy for propagating changes through formula dependencies when an undo or redo triggers a cascade.
Worked scenario
A user deletes row 5. The delete command keeps the contents of row 5 so it can be put back, and also remembers which formulas were altered by the deletion. When the user presses undo, the row returns and the formulas that had been broken are restored to their original references and dependencies.
Constraints
- The sheet may hold up to 100,000 cells.
- The history must not grow without limit; explain how you prevent memory leaks.
Be ready to discuss trade-offs, edge cases (cycles, error values, empty stacks, branching after an undo) and the complexity of each operation.
Hints
Hint 1
Ask which data is primary and which is derived. If a command saves only what the user typed (raw input) and never computed results, snapshots stay small and consistency is easy to restore.
Hint 2
Route every change, including those made by undo, through a small set of sheet operations that update the dependency graph and recalculate in topological order. Then undo needs no special recalculation code.
Hint 3
Deleting a row can rewrite references to an error marker, and that rewrite cannot be reversed by shifting indices back. Think about what extra information the delete command must save, and how history behaves when a new action follows an undo or when an irreversible action occurs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use the Command pattern, with a Memento held inside each command, on top of a sheet that owns a dependency graph and performs recalculation itself.
Three principles drive the design:
- Commands store raw inputs only. A cell's raw input is text like
"42"or"=A1+B2". Computed values are derived state, so they are never saved. Restoring the raw inputs and recalculating always yields a consistent sheet, and snapshots stay small. - All mutations go through sheet primitives. Commands never write to computed values. They call
set_raw,delete_rowandinsert_row, which update the dependency graph and recompute affected cells in topological order. Becauseundo()uses the same primitives asexecute(), recalculation after undo or redo is automatic. - History is two stacks with explicit rules. A bounded undo stack and a redo stack. A new command clears redo. An irreversible command acts as a barrier.
Interfaces
class Command(ABC):
undoable = True
@abstractmethod
def execute(self, sheet): ...
@abstractmethod
def undo(self, sheet): ...
def cost(self): return 1 # approx. number of stored cells
What each command remembers
| Command | Before-state (memento) | After-state |
|---|---|---|
SetCellCommand | old raw text, or None if empty | new raw text |
DeleteRowCommand | raw cells of the removed row, plus the original text of every formula the deletion rewrote (keyed by pre-delete position) | row index |
BatchCommand | list of child commands | none |
PublishCommand | nothing, undoable = False | none |
Why row deletion needs a formula snapshot
Deleting row 5 changes formulas elsewhere. A reference to A5 becomes #REF!, and a reference to A7 becomes A6. The shift is reversible, but the #REF! rewrite destroys information. So the command saves the original text of every rewritten formula. Undo then:
- shifts rows back down (insert-row key shift, the exact inverse of delete's key shift),
- reinserts the saved row contents,
- overwrites the rewritten formulas with their saved originals.
Formulas that the delete did not touch only referenced rows above the deleted row, so neither shift affects them. The dependency graph is rebuilt from raw text, so the broken edges are re-registered exactly.
History management
run(cmd): callcmd.execute(). If undoable, push on the undo stack and clear the redo stack (a new action after an undo discards the old future). If not undoable, clear both stacks, since earlier states can no longer be reached consistently with the outside world.undo(): pop from undo, callundo(), push on redo. No-op if empty.redo(): pop from redo, callexecute(), push on undo. No-op if empty.- Bounded memory: the undo stack is a
dequewith a cost budget (max_cost, measured in stored cells, not command count, because a row delete is much heavier than a single cell edit). When the budget is exceeded, evict the oldest entries withpopleft(). Clearing redo on new actions is the other half of leak prevention.
Recalculation strategy
When a cell's raw text changes:
- Update its precedent and dependent edges (
depsandrdeps). - Collect all transitive dependents by a DFS over
rdeps. - Run Kahn's algorithm over that subgraph to evaluate in topological order.
- Any cells left unprocessed are in a cycle and get
#CYCLE.
Errors propagate: a formula that references an error cell takes on that error, so #REF! cascades and undo clears it.
Correctness argument
- Stack invariant. When
undo()runs on command k, the sheet is exactly as k left it, because later commands were undone in LIFO order and any new command cleared redo. Each memento is therefore applied to the state it was captured against. - Values are always derived. Recalculation rebuilds values from raw input, so a partial cascade cannot leave stale numbers.
- Batches are atomic. A
BatchCommandundoes children in reverse order. If a child fails duringexecute, the batch rolls back children that already ran and never enters history.
Complexity
- SetCell: O(D) time for D transitive dependents; memento is O(1).
- DeleteRow / its undo: O(N) time for N non-empty cells (at most 100k) because keys below the row shift; a simple implementation reloads and recalculates the whole sheet. Space is O(row cells + rewritten formulas).
- History: bounded by
max_cost.
Trade-offs
- Memento vs. inverse operations: saving old state is simpler and robust; computing inverses saves memory but is error-prone for lossy operations like
#REF!. - Full snapshots vs. deltas: snapshots of 100k cells per step would be too costly, so store deltas per command.
- Eager vs. lazy recalculation: eager is simpler; lazy or incremental recomputation helps for very large sheets.
Edge cases
- Undo or redo on an empty stack is a no-op.
- Cycles are marked
#CYCLErather than looped over; undoing the edit clears them. - Setting a cell to empty stores
None, and undo restores the old text. - Edit after undo discards redo.
- Publishing is a barrier: it clears history, or alternatively it could be modeled as a separate compensating action ("unpublish") if the product requires it.
Common mistakes
- Storing computed values in mementos, which can go stale and bloat history.
- Mutating cells directly from commands, bypassing dependency updates.
- Forgetting to clear redo on a new action.
- Counting history by number of commands rather than by size.
- Assuming a reference shift can undo
#REF!without saved originals. - Letting a failed batch leave the sheet half-modified.