KatInterview

Reversible Edit History for a Formula-Driven Grid

Data Structure DesignModel answer
MediumModel answerData Structure Designcommand-patternundo-redomemento

Last 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

  1. Cell edits: changing the content of one cell.
  2. Row removal: deleting a row, including the effect on formulas that point into or below it.
  3. Recalculation: after any undo or redo, every affected formula must show a correct, up-to-date result.
  4. Irreversible actions: operations such as publishing that cannot be taken back.

Deliverables

  • A Command abstraction exposing execute() and undo(), 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.