A greenhouse keeps notes per plant bed ("bed3") with fields like "crop". Staff keep mistyping, so every field gets its own undo button.
Build UndoStore with:
set(key, field, value): write the field. Every call is a change, even with the same value.get(key, field) -> str | None: the current value, orNone.delete(key, field) -> bool: remove the field (True), orFalseif absent (not a change).undo(key, field) -> bool: revert that field's most recent not-yet-undone change, restoring the value it had before (or removing it if it didn't exist).Falseif nothing is left to undo. No redo.fields(key) -> list[str]: current field names, sorted;[]if missing.count() -> int: how many records have at least one field.
s = UndoStore()
s.set("bed3", "crop", "kale")
s.set("bed3", "crop", "chard")
s.set("bed3", "watered", "mon")
s.delete("bed3", "crop") # True
s.get("bed3", "crop") # None
s.undo("bed3", "crop") # True (the delete is undone)
s.get("bed3", "crop") # "chard"
s.undo("bed3", "crop") # True
s.get("bed3", "crop") # "kale"
s.undo("bed3", "crop") # True (the very first set is undone)
s.get("bed3", "crop") # None
s.undo("bed3", "crop") # False (nothing left)
s.fields("bed3") # ["watered"]
s.undo("bed3", "watered") # True
s.count() # 0
⭐ Bonus: a count() that scans the records still passes; a speed test with 60,000 sets and counts earns a star if count() is O(1).
Show hint
besides key -> {field: value}, keep (key, field) -> list of previous values: push the old value (None if missing) before each change; undo pops and restores it. Drop empty records so count() is a len.