KatInterview

Build an Edit History System with Batching

Data Structure DesignModel answer
MediumModel answerData Structure Designundo-redocommand-patternstate-management

Last updated

Implement a command history mechanism supporting single edits, grouped operations, and bidirectional traversal through past states.

You're building an editor that needs to track changes and allow users to step backward and forward through their work.

Design a system that manages a mutable document and maintains edit history. Your implementation should support:

  1. Single operations: apply(op) modifies the document by setting or removing a property on a node
  2. Grouped operations: beginBatch() / commitBatch() so multiple edits can be reversed as one unit
  3. History navigation: undo() reverses the last committed change, redo() reapplies it

The document is a collection of nodes, where each node has properties. An operation specifies a node ID, property name, and new value (or indicates deletion).

Your task:

  • Explain your approach to storing history entries
  • Describe how you'd optimize space when a batch contains many edits to the same property
  • Discuss what happens to redo history when new edits arrive
  • Handle edge cases: empty batches, failures during a batch, nested batch calls
  • Analyze time and space complexity

Example:

doc.apply(Op(node="rect1", key="x", value=100))
doc.apply(Op(node="rect1", key="y", value=200))
doc.undo()  // reverts y=200
doc.undo()  // reverts x=100
doc.redo()  // reapplies x=100

With batching:

doc.beginBatch()
for i in range(500):
    doc.apply(Op(node="rect1", key="x", value=100+i))
doc.commitBatch()
doc.undo()  // reverts all 500 edits in one step

Hints

Hint 1

Consider storing what changed rather than replaying operations

Hint 2

For compression, track only the first and last value for each property within a batch

Hint 3

Two stacks can manage forward and backward movement through history