Build an Edit History System with Batching
Data Structure DesignModel answerLast 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:
- Single operations:
apply(op)modifies the document by setting or removing a property on a node - Grouped operations:
beginBatch()/commitBatch()so multiple edits can be reversed as one unit - 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core pattern is maintaining two stacks: one for changes that can be undone, another for changes that can be redone. Each history entry captures what needs to change to reverse or reapply an edit.
Storing Inverse Information
Rather than storing operations and trying to compute their inverse, capture the before and after state at the moment of change. For each modified property, record:
- The original value (what to restore on undo)
- The new value (what to reapply on redo)
This works because our document model is simple: nodes contain properties, and setting a property to a special sentinel value represents deletion. Every mutation can be described as a transition from one value to another.
Structure: Represent the document as Map<NodeID, Map<PropertyKey, Value>>. Each history entry is a map of (NodeID, PropertyKey) → [oldValue, newValue] pairs.
Batching and Compression
When a batch is active, edits accumulate in a temporary map before being committed. The key optimization: use (node, property) as the map key.
- First edit to a property: store its current value as
old - Subsequent edits to the same property: only update
new
A 500-event mouse drag on x and y coordinates produces exactly 2 records: one for x going from its initial to final value, one for y. This compresses O(operations) down to O(distinct properties touched).
At commit time, filter out any entries where old == new (no net change). If the resulting entry is empty, skip pushing it entirely.
History Navigation
Undo: Pop an entry from the undo stack, restore all old values to the document, push the entry to the redo stack.
Redo: Pop from redo stack, apply all new values, push back to undo stack.
Clearing redo: Any new edit (outside of undo/redo) clears the redo stack. History is linear—once you make a new change after undoing, the "future" branch is discarded.
Nested Batches
Track a depth counter. Each beginBatch() increments it, each commitBatch() decrements. Only when depth returns to zero does the accumulated batch get pushed to history. This flattens nested batches into a single undo step, which matches user expectations (one undo = reverse the entire high-level action).
Failure Handling
Before applying an operation, validate it. If validation fails, raise an error before any mutation occurs.
For batch failures (exception thrown, or explicit abort), iterate through the pending map and restore every old value, then discard the pending map. The document returns to its exact state before beginBatch().
Use a context manager to make this automatic:
with doc.batch():
doc.apply(op1)
doc.apply(op2) # if this raises, batch auto-aborts
Complexity Analysis
Let k = distinct properties touched in a batch, m = total operations in that batch.
Time:
apply(): O(1) per call—lookup old value, write new value, update pending mapcommitBatch(): O(k) to filter no-opsundo()/redo(): O(k) to restore/apply all properties in the entry
Space:
- Each history entry: O(k) instead of O(m)
- Total history: O(entries × average k)
- Pending batch: O(k)
If individual values are large (e.g., long text, complex paths), consider storing structural diffs or using copy-on-write data structures so old and new versions share memory.
Edge Cases
Empty stacks: undo() and redo() return False or do nothing when their respective stacks are empty. Don't raise exceptions—this is normal operation.
No-op batches: If a batch makes changes that all cancel out (old == new for everything), nothing is pushed to history. The redo stack is preserved because no actual edit occurred.
Undo/redo during a batch: Raise an error. You can't navigate history while actively building a new history entry.
Mismatched batch calls: commitBatch() without beginBatch() should raise an error immediately.
Deleting non-existent properties: Treating this as a no-op (old=MISSING, new=MISSING) causes it to be filtered out at commit time.
History size limits: Use a bounded deque for the undo stack to cap memory. When the deque is full, the oldest entry is automatically dropped, which is safe since it's unreachable anyway.
Implementation Sketch
from collections import deque
from contextlib import contextmanager
MISSING = object() # sentinel for "property doesn't exist"
class Op:
def __init__(self, node, key, value=MISSING):
self.node = node
self.key = key
self.value = value # MISSING means delete
class Document:
def __init__(self, max_history=1000):
self.state = {} # node -> {key: value}
self._undo_stack = deque(maxlen=max_history)
self._redo_stack = []
self._pending = None
self._batch_depth = 0
def _read(self, node, key):
return self.state.get(node, {}).get(key, MISSING)
def _mutate(self, node, key, value):
if value is MISSING:
if node in self.state:
self.state[node].pop(key, None)
if not self.state[node]:
del self.state[node]
else:
self.state.setdefault(node, {})[key] = value
def apply(self, op):
slot = (op.node, op.key)
old_val = self._read(op.node, op.key)
self._mutate(op.node, op.key, op.value)
if self._batch_depth > 0:
if slot not in self._pending:
self._pending[slot] = [old_val, op.value]
else:
self._pending[slot][1] = op.value # compress
else:
self._commit_entry({slot: [old_val, op.value]})
def _commit_entry(self, entry):
entry = {k: v for k, v in entry.items() if v[0] != v[1]}
if entry:
self._undo_stack.append(entry)
self._redo_stack.clear()
def beginBatch(self):
if self._batch_depth == 0:
self._pending = {}
self._batch_depth += 1
def commitBatch(self):
if self._batch_depth == 0:
raise RuntimeError("No active batch")
self._batch_depth -= 1
if self._batch_depth == 0:
self._commit_entry(self._pending)
self._pending = None
def abortBatch(self):
if self._batch_depth == 0:
raise RuntimeError("No active batch")
for (node, key), (old_val, _) in self._pending.items():
self._mutate(node, key, old_val)
self._pending = None
self._batch_depth = 0
@contextmanager
def batch(self):
self.beginBatch()
try:
yield
except:
self.abortBatch()
raise
else:
self.commitBatch()
def undo(self):
if self._batch_depth > 0:
raise RuntimeError("Cannot undo during batch")
if not self._undo_stack:
return False
entry = self._undo_stack.pop()
for (node, key), (old_val, _) in reversed(entry.items()):
self._mutate(node, key, old_val)
self._redo_stack.append(entry)
return True
def redo(self):
if self._batch_depth > 0:
raise RuntimeError("Cannot redo during batch")
if not self._redo_stack:
return False
entry = self._redo_stack.pop()
for (node, key), (_, new_val) in entry.items():
self._mutate(node, key, new_val)
self._undo_stack.append(entry)
return True
Why This Works:
The compression strategy preserves correctness because we only care about the net effect on each property. If x goes 10→50→100, we only need to remember 10→100 for undo/redo purposes. Intermediate values are implementation details of how the user arrived at 100.
Clearing redo on new edits maintains the invariant that every entry in the redo stack corresponds to an exact document state reachable by undoing from the current state. A new edit creates a branch, invalidating the previous "future."
Common Mistakes
- Storing operations instead of deltas: Leads to complex inverse logic and fragility when operation semantics change
- Not compressing batches: Uses O(operations) space instead of O(properties)
- Forgetting to clear redo: Creates inconsistent history where redo entries don't match the actual document state
- Not handling nested batches: Results in surprising behavior where sub-actions undo separately
- Mutating before validation: A failed operation in a batch can leave the document in a corrupt partial state