Key-Value Document Store with Batched Undo and Redo
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement a DocumentLayer class in Python that manages an in-memory str -> Any property dictionary with multi-step undo(), redo(), and nestable edit batches.
Supported Methods
DocumentLayer(initial: Optional[Dict[str, Any]] = None)— Initializes the document from a shallow copy ofinitial, or an empty dictionary wheninitialisNone.get(key: str, default: Any = None) -> Any— Returns the value currently stored underkey, ordefaultifkeyis not present.snapshot() -> Dict[str, Any]— Returns a shallow dictionary copy of all currently stored key-value pairs.apply(op: Tuple) -> None— Validates and executes one mutation tuple against the live document:("set", key, value)assignsvaluetokey(creating or overwritingkey;valuemay be any Python object, includingNone).("delete", key)deleteskeyif present, or raisesKeyErrorifkeyis missing.- Any non-tuple, unrecognized operation tag, or tuple of the wrong length raises
ValueError. - Failed
applycalls must leave both the document contents and all batch/undo/redo state untouched.
begin_batch() -> None— Opens a new batch scope. Batches may be nested inside outer batches.commit_batch() -> None— Closes the most recently opened batch scope. If an enclosing outer batch remains open, the inner edits stay part of that outer batch; when the outermost batch closes, all edits since its matchingbegin_batch()collapse into a single undoable step. RaisesRuntimeErrorif no batch is currently open.abort_batch() -> None— Reverts every mutation made since the matchingbegin_batch()(including mutations from inner batches that were already committed into it) and closes that batch scope without modifying committed undo or redo stacks. RaisesRuntimeErrorif no batch is currently open.undo() -> bool— Reverts the most recently committed step, makes it available toredo(), and returnsTrue. ReturnsFalsewhen there are no committed steps to revert. RaisesRuntimeErrorif called while a batch is open.redo() -> bool— Reapplies the most recently undone step, moves it back onto the undo history, and returnsTrue. ReturnsFalsewhen there are no undone steps to reapply. RaisesRuntimeErrorif called while a batch is open.
History & Compression Rules
- Per-key delta storage and batch compression: History storage and
undo()/redo()execution time for a step must scale with the number of distinct keys modified in that step rather than total document size or repeated writes to the same key inside a batch. - No-op suppression: A standalone
applyor an outermostcommit_batch()whose net effect leaves every touched key unchanged must not push an undo step and must not clear existing redo history. Two valuesbeforeandaftercount as unchanged only whenbefore is afteror (type(before) is type(after)andbefore == after); thus replacing1(int) withTrue(bool) or1.0(float) is a real edit. - Linear timeline on new commits: Recording any standalone edit or outermost batch that produces a real net change clears the redo stack.
Examples
Example 1
Input:
layer = DocumentLayer({"theme": "light"})
layer.apply(("set", "zoom", 100))
layer.apply(("set", "theme", "dark"))
u1 = layer.undo()
s1 = layer.snapshot()
r1 = layer.redo()
s2 = layer.snapshot()
u2 = layer.undo()
layer.apply(("delete", "zoom"))
r2 = layer.redo()
s3 = layer.snapshot()
Output:
u1 = True, s1 = {"theme": "light", "zoom": 100}
r1 = True, s2 = {"theme": "dark", "zoom": 100}
u2 = True, r2 = False, s3 = {"theme": "light"}
Explanation: Outside a batch, setting "zoom" and updating "theme" record two separate steps. Undoing reverts "theme" to "light", and redoing restores "dark". After undoing a second time back to {"theme": "light", "zoom": 100}, deleting "zoom" commits a new forward edit, which clears the undone "theme": "dark" step so the final redo() returns False.
Example 2
Input:
layer = DocumentLayer({"width": 50, "label": "card"})
layer.begin_batch()
layer.apply(("set", "width", 80))
layer.apply(("set", "width", 120))
layer.apply(("delete", "label"))
layer.apply(("set", "visible", True))
layer.commit_batch()
s1 = layer.snapshot()
layer.begin_batch()
layer.apply(("set", "width", 999))
layer.abort_batch()
s2 = layer.snapshot()
u1 = layer.undo()
s3 = layer.snapshot()
Output:
s1 = {"width": 120, "visible": True}
s2 = {"width": 120, "visible": True}
u1 = True, s3 = {"width": 50, "label": "card"}
Explanation: The first batch updates "width" twice (50 -> 80 -> 120), deletes "label", and adds "visible". Committing compresses those four operations into one step capturing each touched key's pre-batch and post-batch state. The second batch sets "width" to 999 and aborts, restoring 120 without touching history. A single undo() then reverts the entire first batch back to {"width": 50, "label": "card"}.
Constraints
- A document may hold up to
10^5live keys, while individual steps or batches typically touch far fewer keysm << D. undo()andredo()must run inO(m)time for a step that changedmdistinct keys, independent of total document sizeDand independent of how many times each key was overwritten within a batch.- Keys are strings; values may be arbitrary Python objects, including
None, booleans, numbers, strings, tuples, or containers. - Batches may nest arbitrarily deep via matching
begin_batch()andcommit_batch()/abort_batch()calls.
Step-by-step walkthrough
Clarify the operations and undo/redo contract
Before writing any history logic, pin down what the document looks like and how every edge case behaves. Here a document layer is a
key -> valuedictionary (like properties on an interface element:{"width": 120, "theme": "dark"}), using Python snake_case method names (begin_batch,commit_batch,abort_batch) matchingstarter.py:- Supported edits in
apply(op):("set", key, value)sets or overwriteskey(wherevaluecan be anything, includingNone).("delete", key)removeskey, or raisesKeyErrorifkeyis not present.- Any other
opraisesValueErrorwithout changing the document or history.
- Units of work: Outside a batch, each
apply(op)that actually changes the document is one undo step. Betweenbegin_batch()andcommit_batch(), all edits collapse into one undo step. Batches can nest; only the outermostcommit_batch()pushes a step. - Redo rules:
undo()reverts the latest committed step and makes it available toredo(). Committing any new real change clears the redo history. - No-op suppression: Setting a key to its exact current value — or committing a batch whose net result leaves the document unchanged — records no step and leaves
redointact. (Note that in Python1 == True == 1.0, so replacing1withTrueis a real type change!) - Empty stacks and invalid states:
undo()andredo()returnFalsewhen nothing is available (Trueotherwise). Callingundo()/redo()while a batch is open, orcommit_batch()/abort_batch()with no open batch, raisesRuntimeError.
- Supported edits in
Why whole-document snapshots waste memory and time
The naive brute-force approach copies the entire
self.docdictionary before and after every step. That is easy to reason about (and makes a great test oracle!), but its cost scales with total document sizeDrather than edit size:Suppose a document has D = 10,000 keys, and 100 undo steps each modify 3 keys: Whole-document snapshots: 100 steps x 2 copies x 10,000 keys = 2,000,000 stored entries 1 undo() copies 10,000 keys Per-key inverse deltas: 100 steps x 3 changed keys = 300 stored records 1 undo() updates 3 keysBoth memory and
undo()/redo()speed should be proportional to the keys actually changed, independent of how large the rest of the document grows.Represent reversible changes with (key, before, after) and MISSING
For every key modified in a committed step, we store a 3-tuple
(key, before, after): - Toundothe step: writebeforeback tokey. - Toredothe step: writeafterback tokey.One subtle trap: what if
"theme"did not exist before("set", "theme", None)? If we usedNoneto mean "key was absent", we could never tell the difference between "key was absent" and "key existed with valueNone". Introducing a private singleton objectMISSINGsolves bothsetanddeleteuniformly: - Creating a new key"m"withNonerecords("m", MISSING, None). - Deleting"label"(which held"card") records("label", "card", MISSING). - WritingMISSINGin_writesimply deletes the key!We also validate
opinside_target(op)before touchingself.docso a baddeleteor malformed tuple fails cleanly with zero side effects:class _Missing: def __repr__(self) -> str: return "MISSING" MISSING = _Missing() def _unchanged(before: Any, after: Any) -> bool: # 1 == 1.0 == True in Python, so check exact runtime type alongside '=='. if before is after: return True return type(before) is type(after) and before == after def _target(self, op: Tuple) -> Tuple[str, Any]: """Validate op and return (key, value_to_write); MISSING represents deletion.""" if not isinstance(op, tuple): raise ValueError(f"unknown op {op!r}") if len(op) == 3 and op[0] == "set": return op[1], op[2] if len(op) == 2 and op[0] == "delete": if op[1] not in self.doc: raise KeyError(op[1]) return op[1], MISSING raise ValueError(f"unknown op {op!r}") def _write(self, key: str, value: Any) -> None: """Write value into self.doc, or delete key when value is MISSING.""" if value is MISSING: self.doc.pop(key, None) else: self.doc[key] = valueManage history with undo and redo stacks
Maintain two stacks of steps (
undo_stackandredo_stack), where each step is a list[(key, before, after), ...]:1. apply(set a=1), apply(set a=2): doc={a:2} undo_stack=[ [(a,MISSING,1)], [(a,1,2)] ] redo_stack=[] 2. undo(): pops [(a,1,2)], writes before=1, pushes to redo_stack: doc={a:1} undo_stack=[ [(a,MISSING,1)] ] redo_stack=[ [(a,1,2)] ] 3. apply(set b=9): new timeline! Pushes [(b,MISSING,9)] and CLEARS redo_stack: doc={a:1,b:9} undo_stack=[ [(a,MISSING,1)], [(b,MISSING,9)] ] redo_stack=[]Why must a new edit clear
redo_stack? Because history is a linear timeline: once you undoa: 1 -> 2back toa = 1and then seta = 99, reapplyinga: 1 -> 2would silently overwrite99, and undoing it would restore1instead of99, corrupting history. (Preserving forked timelines requires an explicit undo tree UI.)def undo(self) -> bool: self._require_no_batch("undo") if not self.undo_stack: return False step = self.undo_stack.pop() for key, before, after in step: self._write(key, before) self.redo_stack.append(step) return True def redo(self) -> bool: self._require_no_batch("redo") if not self.redo_stack: return False step = self.redo_stack.pop() for key, before, after in step: self._write(key, after) self.undo_stack.append(step) return TrueSupport nested batches with a log and mark stack
While a batch is open,
applymutatesself.docimmediately (soget()inside the batch sees live updates) and appends(key, before)toself.batch_log.To support nested batches cleanly — for example, a helper method wrapping its own
begin_batch()/commit_batch()when called inside an outer drag gesture — keepself.batch_marks, a stack storinglen(self.batch_log)at eachbegin_batch():Call batch_log batch_marks ---- --------- ----------- begin_batch() (outer) [] [0] apply(set a=2) [(a, 1)] [0] begin_batch() (inner) [(a, 1)] [0, 1] apply(set b=3) [(a, 1), (b, MISSING)] [0, 1] commit_batch() (inner)[(a, 1), (b, MISSING)] [0] <-- inner entries absorbed into outer! apply(set c=4) [(a, 1), (b, MISSING), (c, MISSING)] [0] commit_batch() (outer) [] --> compresses & pushes 1 combined step! []An inner
commit_batch()simply pops its mark and returns becauseself.batch_marksis still non-empty. Only when the outermost mark is popped doescommit_batch()compressself.batch_logand record one undo step:def begin_batch(self) -> None: self.batch_marks.append(len(self.batch_log)) def commit_batch(self) -> None: if not self.batch_marks: raise RuntimeError("commit_batch() without an open batch") self.batch_marks.pop() if self.batch_marks: return # Inner batch committed into enclosing outer batch changes = self._compress(self.batch_log) self.batch_log = [] if changes: self._record(changes)Notice that overlapping non-nested batches (
begin A -> begin B -> commit A -> commit B) cannot occur with unnamedbegin_batch()/commit_batch()calls because commits are strictly last-in, first-out.Compress consecutive batch edits to one record per key
Imagine dragging a shape across a canvas inside one batch:
xchanges5 -> 10 -> 18 -> ... -> 30across 60applycalls, and a temporary guide key"snap"is created (MISSING -> 1) and deleted (1 -> MISSING) before mouse release.Storing all 62 raw operations wastes memory and makes every future
undo()/redo()replay 62 writes. Instead,_compresscollapses the entire batch to at most one(key, before, after)tuple per distinct key: 1. Scanbatch_logleft-to-right and record only the very firstbeforevalue seen for each key (x -> 5,snap -> MISSING). 2. Look up each key's final value inself.docright now (x -> 30,snap -> MISSING). 3. Keep the key only ifnot _unchanged(before, after)— so"snap"(MISSING -> MISSING) vanishes completely, and 60 moves of"x"shrink to one tuple("x", 5, 30)!def _compress(self, log): first_before = {} for key, before in log: if key not in first_before: first_before[key] = before changes = [] for key, before in first_before.items(): after = self.doc.get(key, MISSING) if not _unchanged(before, after): changes.append((key, before, after)) return changesBe careful never to overwrite
first_before[key]on later edits: keeping the lastbeforeon5 -> 10 -> 30would store10, causingundo()to stop halfway at10instead of returning to5!Handle partial failures and newest-first batch rollback
Partial failures happen at two levels: 1. Single invalid
apply(op): Because_target(op)validates the tuple and checks key existence before_writeruns, a failing call leavesself.docandself.batch_loguntouched. If a batch was open, the caller can catch the error and either continue or callabort_batch(). 2. Rolling back an open batch (abort_batch()): Popmark = self.batch_marks.pop()and undo every log entry aftermarkfrom newest to oldest:Suppose a starts at 1 inside an open batch (mark = 0): apply(set a=2) -> doc={a:2}, batch_log=[(a, 1)] apply(set a=3) -> doc={a:3}, batch_log=[(a, 1), (a, 2)] abort_batch() pops newest-first: pop (a, 2) -> writes a=2 pop (a, 1) -> writes a=1 --> doc={a:1} (exact pre-batch state restored!) (Replaying oldest-first would write 1 then 2, leaving a=2!)If an inner batch aborts,
markstops right at the innerbegin_batch(), preserving earlier outer-batch edits. If an outer batch aborts,marksits before any already-committed inner batches, rolling those back too — and because nothing was committed toundo_stack, any existingredo_stackstays intact!def abort_batch(self) -> None: if not self.batch_marks: raise RuntimeError("abort_batch() without an open batch") mark = self.batch_marks.pop() # Replay log entries backwards (newest -> oldest) so repeated edits to one key restore # its value from right before the matching begin_batch(). while len(self.batch_log) > mark: key, before = self.batch_log.pop() self._write(key, before)Let's trace Example 2 from the statement starting from
{"width": 50, "label": "card"}:Call Live self.doc undo_stack redo_stack ---- ------------- ---------- ---------- begin_batch() {width:50, label:"card"} (mark=0, log=[]) apply(set width=80) {width:80, label:"card"} (log=[(width,50)]) apply(set width=120) {width:120, label:"card"} (log=[(width,50), (width,80)]) apply(delete label) {width:120} (log=[(width,50), (width,80), (label,"card")]) apply(set visible=True) {width:120, visible:True} (log=[..., (visible,MISSING)]) commit_batch() {width:120, visible:True} [ [(width,50,120),(label,"card",MISSING),(visible,MISSING,True)] ] [] begin_batch() {width:120, visible:True} (mark=0, log=[]) apply(set width=999) {width:999, visible:True} (log=[(width,120)]) abort_batch() {width:120, visible:True} [ [(width,50,120),...] ] [] undo() -> True {width:50, label:"card"} [] [ [(width,50,120),...] ]Complete solution
from typing import Any, Dict, List, Optional, Tuple class _Missing: def __repr__(self) -> str: return "MISSING" # Private sentinel marking "key was absent in self.doc", so None can be stored as a normal value. MISSING = _Missing() def _unchanged(before: Any, after: Any) -> bool: # In Python, 1 == 1.0 == True, so plain '==' would treat 1 -> True as a no-op! # Require either identical object identity OR exact same runtime type plus '=='. if before is after: return True return type(before) is type(after) and before == after class DocumentLayer: def __init__(self, initial: Optional[Dict[str, Any]] = None) -> None: # self.doc: current live document map, e.g. {"width": 120, "theme": "dark"} self.doc: Dict[str, Any] = dict(initial) if initial is not None else {} # self.undo_stack: committed steps oldest -> newest; each step is [(key, before, after), ...] self.undo_stack: List[List[Tuple[str, Any, Any]]] = [] # self.redo_stack: undone steps oldest -> newest; cleared whenever a real new step commits self.redo_stack: List[List[Tuple[str, Any, Any]]] = [] # self.batch_log: raw [(key, before), ...] entries appended while at least one batch is open self.batch_log: List[Tuple[str, Any]] = [] # self.batch_marks: stack of len(self.batch_log) positions at each open begin_batch() self.batch_marks: List[int] = [] def get(self, key: str, default: Any = None) -> Any: return self.doc.get(key, default) def snapshot(self) -> Dict[str, Any]: return dict(self.doc) def apply(self, op: Tuple) -> None: # Validate op BEFORE mutating self.doc or history so failed ops have zero side effects. key, after = self._target(op) before = self.doc.get(key, MISSING) self._write(key, after) if self.batch_marks: # Inside an open batch: log (key, before) so abort_batch() or commit_batch() can use it. self.batch_log.append((key, before)) elif not _unchanged(before, after): # Standalone edit with a real net change: record one undo step and clear redo history. self._record([(key, before, after)]) def begin_batch(self) -> None: # Save the current log length so inner commit/abort knows where this batch began. self.batch_marks.append(len(self.batch_log)) def commit_batch(self) -> None: if not self.batch_marks: raise RuntimeError("commit_batch() without an open batch") self.batch_marks.pop() # If an outer batch is still open, keep batch_log intact as part of the enclosing batch. if self.batch_marks: return # Outermost batch closed: compress consecutive edits per key into one minimal step. changes = self._compress(self.batch_log) self.batch_log = [] if changes: self._record(changes) def abort_batch(self) -> None: if not self.batch_marks: raise RuntimeError("abort_batch() without an open batch") mark = self.batch_marks.pop() # Replay log entries backwards (newest -> oldest) so repeated edits to one key restore # its value from right before the matching begin_batch(). while len(self.batch_log) > mark: key, before = self.batch_log.pop() self._write(key, before) def undo(self) -> bool: self._require_no_batch("undo") if not self.undo_stack: return False step = self.undo_stack.pop() for key, before, after in step: self._write(key, before) self.redo_stack.append(step) return True def redo(self) -> bool: self._require_no_batch("redo") if not self.redo_stack: return False step = self.redo_stack.pop() for key, before, after in step: self._write(key, after) self.undo_stack.append(step) return True def _target(self, op: Tuple) -> Tuple[str, Any]: """Validate op and return (key, value_to_write); MISSING represents deletion.""" if not isinstance(op, tuple): raise ValueError(f"unknown op {op!r}") if len(op) == 3 and op[0] == "set": return op[1], op[2] if len(op) == 2 and op[0] == "delete": if op[1] not in self.doc: raise KeyError(op[1]) return op[1], MISSING raise ValueError(f"unknown op {op!r}") def _write(self, key: str, value: Any) -> None: """Write value into self.doc, or delete key when value is MISSING.""" if value is MISSING: self.doc.pop(key, None) else: self.doc[key] = value def _compress(self, log: List[Tuple[str, Any]]) -> List[Tuple[str, Any, Any]]: """Collapse a batch log to at most one (key, first_before, current_after) record per key.""" first_before: Dict[str, Any] = {} for key, before in log: # Keep only the VERY FIRST 'before' seen for each key in this batch. if key not in first_before: first_before[key] = before changes: List[Tuple[str, Any, Any]] = [] for key, before in first_before.items(): after = self.doc.get(key, MISSING) # Drop keys whose final value at commit equals their starting value before the batch. if not _unchanged(before, after): changes.append((key, before, after)) return changes def _record(self, changes: List[Tuple[str, Any, Any]]) -> None: self.undo_stack.append(changes) self.redo_stack.clear() def _require_no_batch(self, name: str) -> None: if self.batch_marks: raise RuntimeError(f"{name}() while a batch is open")✅ Submit now — all tests should pass.
Intuition & how it works
Think of editing a large design canvas like updating sticky fields in a 500-page binder. Photocopying all 500 pages before every single edit would fill a filing cabinet in minutes; instead, you keep a stack of tiny index cards where each card records only what changed ("width: was 50, became 120"). Pressing Undo reads the top card to write 50 back and moves that card onto a Redo pile; pressing Redo writes 120 back and returns the card to the Undo pile. While you resize a card across 60 mouse-move frames inside a batch (a group of edits bundled so they commit or roll back as one atomic unit), you jot scratch notes during the drag and compress all 60 frames down to a single "width: 50 -> 120" index card the moment you release the mouse.
The naive snapshot approach — copying the entire document dictionary on every apply — takes O(D) time and O(D) memory per edit on a D-key document, turning tiny property tweaks on large documents into multi-megabyte copies. Storing uncompressed operation lists inside batches is also wasteful: resizing width across 60 coordinates would store 60 entries and replay all 60 during every undo() and redo(). Recording inverse deltas (key, before, after) with a private sentinel object MISSING (a unique marker object standing for "key did not exist", distinct from None) plus per-key batch compression shrinks both memory and undo time to the exact number of distinct keys changed.
Walk through 5 events starting from {"width": 50, "label": "card"}:
1. begin_batch(), apply(("set", "width", 80)), apply(("set", "width", 120)), apply(("delete", "label")), apply(("set", "visible", True)), commit_batch() compresses the two "width" writes into their first before (50) and final after (120), pushing one combined step [("width", 50, 120), ("label", "card", MISSING), ("visible", MISSING, True)].
2. Opening a second batch with apply(("set", "width", 999)) and calling abort_batch() restores "width" to 120 without touching undo_stack or redo_stack.
3. undo() pops the committed batch step, restores "width" to 50, puts "label": "card" back, deletes "visible" (because its before is MISSING), and moves the step to redo_stack.
4. redo() pops the step from redo_stack, restores {"width": 120, "visible": True}, and pushes it back to undo_stack.
5. If we instead undo() back to {"width": 50, "label": "card"} and then apply(("set", "theme", "dark")), committing that new timeline clears redo_stack so a subsequent redo() cleanly returns False.
Complexity
apply(op): O(1) amortized time. Validating the tuple, looking upbeforeinself.doc, updatingself.doc, and appending tobatch_logorundo_stackare all constant-time dictionary/list operations. Clearingredo_stackon a standalone edit is amortizedO(1)(meaning its total cost averaged across the sequence of operations is constant per call) because every entry cleared fromredo_stackwas placed there by an earlierundo()call at most once.begin_batch()and innercommit_batch(): O(1) time, because each call simply appends or pops one integer index onself.batch_marks.- Outermost
commit_batch(): O(b) time, wherebis the total number ofapplycalls inside the batch, because_compressscans theblog entries once to capture the firstbeforeper key and then loops once over them <= bdistinct touched keys. abort_batch(): O(e) time, whereeis the number ofapplycalls made since the matchingbegin_batch(), popping and reverting each entry once in reverse order.undo()andredo(): O(m) time, wheremis the number of distinct keys whose net value changed in that step — completely independent of total document sizeDand independent of how many times a key was overwritten inside a batch!- Space: O(D + M + b), where
Dis the number of live keys inself.doc,Mis the sum of distinct changed keys across all steps currently inundo_stackandredo_stack, andbis the length of any currently openbatch_log.
Edge cases
- Empty undo or redo stack:
undo()andredo()returnFalsewithout raising or modifyingself.doc. - No-op edits and self-canceling batches: Setting
"a"to1when"a"is already1, committing an empty batch, or runningset k=1followed bydelete kon an absent key inside one batch produces zero net change — so no step is pushed and any existingredo_stackstays untouched. - Python
1 == True == 1.0type equality: Plainbefore == afterin Python considers1,True, and1.0equal! Checkingtype(before) is type(after) and before == afterensures changing1toTrueis properly recorded and undoable. Nonestored as a legitimate value: Using the privateMISSINGsentinel separates{"n": None}(before = None) from{}(before = MISSING), so undoing("set", "m", None)deletes"m"rather than leaving{"m": None}.- Nested batches and partial aborts: An inner
commit_batch()merges into its enclosing batch so one outerundo()reverts everything; an innerabort_batch()rolls back only down to the inner mark while keeping outer edits; an outerabort_batch()rolls back even inner batches that already committed into it. - Overlapping (non-nested) batches: Anonymous
begin_batch()/commit_batch()calls enforce strict last-in, first-out nesting by construction. Supporting truly concurrent interleaved batches from two independent tools would require returning explicitbatch_idtokens and tracking per-batch logs. - Failed
applycalls and lifecycle misuse: Deleting a missing key (KeyError) or passing an invalid tuple (ValueError) validates before mutating anything; callingundo/redoduring an open batch orcommit_batch/abort_batchwithout one raisesRuntimeError.
Common mistakes
- Overwriting
beforeinstead of keeping the firstbeforeduring batch compression: Ifxchanges0 -> 10 -> 30and you store the latestbefore(10),undo()stops at the intermediate state10instead of restoring0. - Replaying
abort_batch()oldest-first instead of newest-first: Ona: 1 -> 2 -> 3,batch_logholds[("a", 1), ("a", 2)]; iterating forward writes1and then overwrites it with2! Popping from the end writes2then1. - Using
Noneas the "deleted/absent" marker: Breaks as soon as a user sets a key's value toNone. - Forgetting to clear
redo_stackon a new committed edit (or clearing it on no-op edits): Keeping stale redo steps after a new edit overwrites newer work, while clearing redo on a no-op edit surprises users when nothing actually changed. - Pushing a separate undo step on inner
commit_batch(): Breaks the guarantee that an outer batch undoes in a singleundo()call. - Mutating
self.docorbatch_logbefore validatingop: Leaves corrupted partial state behind after an exception.
Follow-up questions
- How can you cap memory consumption when a user keeps editing for hours? Replace the unbounded
undo_stacklist with acollections.deque(maxlen=MAX_STEPS)to cap step count automatically, or track a running record/byte count and evict steps from the front (popleft()) while total memory exceeds a budget (such as 50 MB). To boundbatch_logeven if a caller streams thousands of updates into one open batch without nested marks, keep a per-batchfirst_beforedictionary (O(m)unique keys instead ofO(b)raw edits). If deep history matters, spill evicted old steps sequentially to a local disk log. - How would you merge rapid consecutive single-key tweaks (such as typing or arrow-key nudges) without requiring explicit batch calls? Edit coalescing merges consecutive single-key steps that touch the same key within a short time threshold (say
300–500 ms) when noundo()orredo()occurred in between. When a new standalone edit(key, before, after)arrives within the window andundo_stack[-1]is a single-key step on that samekey, keepundo_stack[-1]'s originalbeforeand replace itsafterwith the newafter(dropping the step entirely if_unchanged(original_before, new_after)becomes true). - How do undo and redo rules change in a real-time collaborative editor with multiple active users? In multiplayer editing, pressing Undo must revert your own most recent action (local undo), not a teammate's edit made 100 ms ago on the other side of the canvas. That means each user maintains a per-user undo stack of inverse operations rather than reverting global document snapshots, and undoing an operation broadcasts a new forward edit to peers. If a collaborator modified
"theme"after your edit (current_value != your_recorded_after), blindly writingyour_beforewould clobber their work — so production multiplayer systems either transform operations via Operational Transformation (OT) / CRDTs (conflict-free replicated data structures for concurrent edits) or skip/rebase conflicted properties according to last-writer rules.
Alternative approaches
- Single history array with a cursor index: Store one list
history = [step_0, step_1, ...]plus an integercursor.undo()decrementscursorand appliesbefore;redo()appliesafterand incrementscursor; recording a new step slicesdel history[cursor:]and appends. It is isomorphic to two stacks with identical time and space complexity. - Per-frame
first_beforemaps forO(unique_keys)open-batch memory: Instead of appending every edit tobatch_log, push onedictonto a stack at eachbegin_batch(), recordingframe.setdefault(key, before)on first touch in that batch level. Onabort_batch(), writeframe.items()back; on innercommit_batch(), merge the childframeintoparent_frameviaparent_frame.setdefault(k, v). This bounds open-batch memory by unique keys touched per nesting level rather than raw mouse-drag ticks. - Persistent immutable trees (structural sharing): Represent the document with a persistent hash-array mapped trie (HAMT) where each update creates a new root sharing unchanged subtrees in
O(log D)nodes. Single-userundo()andredo()becomeO(1)pointer swaps between root references with zero inverse-operation logic, at the cost ofO(log D)allocations per edit.
Follow-up questions
- How can you cap memory consumption when a user keeps editing for hours?
- How would you merge rapid consecutive single-key tweaks (such as typing or arrow-key nudges) without requiring explicit batch calls?
- How do undo and redo rules change in a real-time collaborative editor with multiple active users?
Similar questions
- Permission Graph Path Reachability
- Nested Outline from Depth-Tagged Entries
- Batched Layer History and Grid Regions
- Check Properly Nested INDENT and DEDENT Markers
- Earliest File Shares and Closest Collaborators
- Core Hiring-Manager Behavioral Prompts
More Figma interview questions
- Agent Post-Training ML Screen: System Ownership, Trade-Offs, and Evaluation Rigor Hard
- Core Hiring-Manager Behavioral Prompts Medium
- Measurement Framework for AI Layer-Naming Productivity Medium Pro
- Nested Outline from Depth-Tagged Entries Medium Pro
- Authorization-Safe Search for Collaborative Design Workspaces Medium Pro
- Near-Real-Time Trending Articles Service Hard Pro
- Evaluation Infrastructure for an AI Canvas-Editing Agent Medium Pro
- Navigating Stakeholder Disagreement on Data Findings Medium Pro
- End-to-End Data Science Project Presentation Medium Pro
- Check Properly Nested INDENT and DEDENT Markers Medium Pro