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 of initial, or an empty dictionary when initial is None.
  • get(key: str, default: Any = None) -> Any — Returns the value currently stored under key, or default if key is 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) assigns value to key (creating or overwriting key; value may be any Python object, including None).
    • ("delete", key) deletes key if present, or raises KeyError if key is missing.
    • Any non-tuple, unrecognized operation tag, or tuple of the wrong length raises ValueError.
    • Failed apply calls 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 matching begin_batch() collapse into a single undoable step. Raises RuntimeError if no batch is currently open.
  • abort_batch() -> None — Reverts every mutation made since the matching begin_batch() (including mutations from inner batches that were already committed into it) and closes that batch scope without modifying committed undo or redo stacks. Raises RuntimeError if no batch is currently open.
  • undo() -> bool — Reverts the most recently committed step, makes it available to redo(), and returns True. Returns False when there are no committed steps to revert. Raises RuntimeError if called while a batch is open.
  • redo() -> bool — Reapplies the most recently undone step, moves it back onto the undo history, and returns True. Returns False when there are no undone steps to reapply. Raises RuntimeError if called while a batch is open.

History & Compression Rules

  1. 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.
  2. No-op suppression: A standalone apply or an outermost commit_batch() whose net effect leaves every touched key unchanged must not push an undo step and must not clear existing redo history. Two values before and after count as unchanged only when before is after or (type(before) is type(after) and before == after); thus replacing 1 (int) with True (bool) or 1.0 (float) is a real edit.
  3. 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^5 live keys, while individual steps or batches typically touch far fewer keys m << D.
  • undo() and redo() must run in O(m) time for a step that changed m distinct keys, independent of total document size D and 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() and commit_batch() / abort_batch() calls.

Step-by-step walkthrough

  1. 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 -> value dictionary (like properties on an interface element: {"width": 120, "theme": "dark"}), using Python snake_case method names (begin_batch, commit_batch, abort_batch) matching starter.py:

    • Supported edits in apply(op):
      • ("set", key, value) sets or overwrites key (where value can be anything, including None).
      • ("delete", key) removes key, or raises KeyError if key is not present.
      • Any other op raises ValueError without changing the document or history.
    • Units of work: Outside a batch, each apply(op) that actually changes the document is one undo step. Between begin_batch() and commit_batch(), all edits collapse into one undo step. Batches can nest; only the outermost commit_batch() pushes a step.
    • Redo rules: undo() reverts the latest committed step and makes it available to redo(). 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 redo intact. (Note that in Python 1 == True == 1.0, so replacing 1 with True is a real type change!)
    • Empty stacks and invalid states: undo() and redo() return False when nothing is available (True otherwise). Calling undo()/redo() while a batch is open, or commit_batch()/abort_batch() with no open batch, raises RuntimeError.
  2. Why whole-document snapshots waste memory and time

    The naive brute-force approach copies the entire self.doc dictionary before and after every step. That is easy to reason about (and makes a great test oracle!), but its cost scales with total document size D rather 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 keys
    

    Both memory and undo()/redo() speed should be proportional to the keys actually changed, independent of how large the rest of the document grows.

  3. 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): - To undo the step: write before back to key. - To redo the step: write after back to key.

    One subtle trap: what if "theme" did not exist before ("set", "theme", None)? If we used None to mean "key was absent", we could never tell the difference between "key was absent" and "key existed with value None". Introducing a private singleton object MISSING solves both set and delete uniformly: - Creating a new key "m" with None records ("m", MISSING, None). - Deleting "label" (which held "card") records ("label", "card", MISSING). - Writing MISSING in _write simply deletes the key!

    We also validate op inside _target(op) before touching self.doc so a bad delete or 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] = value
    
  4. Manage history with undo and redo stacks

    Maintain two stacks of steps (undo_stack and redo_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 undo a: 1 -> 2 back to a = 1 and then set a = 99, reapplying a: 1 -> 2 would silently overwrite 99, and undoing it would restore 1 instead of 99, 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 True
    
  5. Support nested batches with a log and mark stack

    While a batch is open, apply mutates self.doc immediately (so get() inside the batch sees live updates) and appends (key, before) to self.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 — keep self.batch_marks, a stack storing len(self.batch_log) at each begin_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 because self.batch_marks is still non-empty. Only when the outermost mark is popped does commit_batch() compress self.batch_log and 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 unnamed begin_batch() / commit_batch() calls because commits are strictly last-in, first-out.

  6. Compress consecutive batch edits to one record per key

    Imagine dragging a shape across a canvas inside one batch: x changes 5 -> 10 -> 18 -> ... -> 30 across 60 apply calls, 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, _compress collapses the entire batch to at most one (key, before, after) tuple per distinct key: 1. Scan batch_log left-to-right and record only the very first before value seen for each key (x -> 5, snap -> MISSING). 2. Look up each key's final value in self.doc right now (x -> 30, snap -> MISSING). 3. Keep the key only if not _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 changes
    

    Be careful never to overwrite first_before[key] on later edits: keeping the last before on 5 -> 10 -> 30 would store 10, causing undo() to stop halfway at 10 instead of returning to 5!

  7. 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 _write runs, a failing call leaves self.doc and self.batch_log untouched. If a batch was open, the caller can catch the error and either continue or call abort_batch(). 2. Rolling back an open batch (abort_batch()): Pop mark = self.batch_marks.pop() and undo every log entry after mark from 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, mark stops right at the inner begin_batch(), preserving earlier outer-batch edits. If an outer batch aborts, mark sits before any already-committed inner batches, rolling those back too — and because nothing was committed to undo_stack, any existing redo_stack stays 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),...] ]
    
  8. 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 up before in self.doc, updating self.doc, and appending to batch_log or undo_stack are all constant-time dictionary/list operations. Clearing redo_stack on a standalone edit is amortized O(1) (meaning its total cost averaged across the sequence of operations is constant per call) because every entry cleared from redo_stack was placed there by an earlier undo() call at most once.
  • begin_batch() and inner commit_batch(): O(1) time, because each call simply appends or pops one integer index on self.batch_marks.
  • Outermost commit_batch(): O(b) time, where b is the total number of apply calls inside the batch, because _compress scans the b log entries once to capture the first before per key and then loops once over the m <= b distinct touched keys.
  • abort_batch(): O(e) time, where e is the number of apply calls made since the matching begin_batch(), popping and reverting each entry once in reverse order.
  • undo() and redo(): O(m) time, where m is the number of distinct keys whose net value changed in that step — completely independent of total document size D and independent of how many times a key was overwritten inside a batch!
  • Space: O(D + M + b), where D is the number of live keys in self.doc, M is the sum of distinct changed keys across all steps currently in undo_stack and redo_stack, and b is the length of any currently open batch_log.

Edge cases

  • Empty undo or redo stack: undo() and redo() return False without raising or modifying self.doc.
  • No-op edits and self-canceling batches: Setting "a" to 1 when "a" is already 1, committing an empty batch, or running set k=1 followed by delete k on an absent key inside one batch produces zero net change — so no step is pushed and any existing redo_stack stays untouched.
  • Python 1 == True == 1.0 type equality: Plain before == after in Python considers 1, True, and 1.0 equal! Checking type(before) is type(after) and before == after ensures changing 1 to True is properly recorded and undoable.
  • None stored as a legitimate value: Using the private MISSING sentinel 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 outer undo() reverts everything; an inner abort_batch() rolls back only down to the inner mark while keeping outer edits; an outer abort_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 explicit batch_id tokens and tracking per-batch logs.
  • Failed apply calls and lifecycle misuse: Deleting a missing key (KeyError) or passing an invalid tuple (ValueError) validates before mutating anything; calling undo/redo during an open batch or commit_batch/abort_batch without one raises RuntimeError.

Common mistakes

  • Overwriting before instead of keeping the first before during batch compression: If x changes 0 -> 10 -> 30 and you store the latest before (10), undo() stops at the intermediate state 10 instead of restoring 0.
  • Replaying abort_batch() oldest-first instead of newest-first: On a: 1 -> 2 -> 3, batch_log holds [("a", 1), ("a", 2)]; iterating forward writes 1 and then overwrites it with 2! Popping from the end writes 2 then 1.
  • Using None as the "deleted/absent" marker: Breaks as soon as a user sets a key's value to None.
  • Forgetting to clear redo_stack on 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 single undo() call.
  • Mutating self.doc or batch_log before validating op: 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_stack list with a collections.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 bound batch_log even if a caller streams thousands of updates into one open batch without nested marks, keep a per-batch first_before dictionary (O(m) unique keys instead of O(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 no undo() or redo() occurred in between. When a new standalone edit (key, before, after) arrives within the window and undo_stack[-1] is a single-key step on that same key, keep undo_stack[-1]'s original before and replace its after with the new after (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 writing your_before would 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 integer cursor. undo() decrements cursor and applies before; redo() applies after and increments cursor; recording a new step slices del history[cursor:] and appends. It is isomorphic to two stacks with identical time and space complexity.
  • Per-frame first_before maps for O(unique_keys) open-batch memory: Instead of appending every edit to batch_log, push one dict onto a stack at each begin_batch(), recording frame.setdefault(key, before) on first touch in that batch level. On abort_batch(), write frame.items() back; on inner commit_batch(), merge the child frame into parent_frame via parent_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-user undo() and redo() become O(1) pointer swaps between root references with zero inverse-operation logic, at the cost of O(log D) allocations per edit.

Follow-up questions

Similar questions

More Figma interview questions

All 29 Figma questions →