Build an In-Memory Notebook System with Rollback
Data Structure DesignModel answerLast updated
Design and implement a versioned in-memory notebook system supporting CRUD, case-insensitive search, user management, and full state rollback via a change log.
In-Memory Notebook System with Version History
You are building a lightweight in-memory Notebook Management System. No database or file I/O is required — everything lives in memory. Implement it as a class with the methods described below, adding features level by level.
Data model
A Notebook has:
notebook_id— unique string identifiertitle— stringpage_count— integer (used for sorting)
A Member has:
member_id— unique string identifiermember_name— string
Level 1 — Core CRUD
Implement the four fundamental operations:
add_notebook(notebook)— add a new notebook. Clearly state what happens ifnotebook_idis already taken.update_notebook(notebook_id, **fields)— update one or more fields of an existing notebook.get_notebook(notebook_id)— retrieve a notebook by id, or signal that it does not exist.delete_notebook(notebook_id)— remove a notebook from the system.
Describe your behavior for edge cases: updating or deleting a notebook that does not exist, updating with an unrecognized field name.
Level 2 — Search and listing
search_notebooks(query)— find notebooks whosetitlecontainsquery(case-insensitive substring match). An empty query should match everything.list_notebooks(sort_by)— return all notebooks sorted by:"title"— lexicographic, case-insensitive, ties broken bynotebook_id"page_count"— numeric ascending, ties broken bynotebook_id- Any other value is an error.
Level 3 — Members
add_member(member)— add a member to the system. State your behavior on duplicatemember_id.
Level 4 — Versioning and rollback
Every successful mutating operation (add, update, delete notebook; add member) creates a new version. Implement:
version_history()— return a list of version metadata, at minimum a monotonically increasingversion_idand a human-readable description of what changed.rollback(version_id)— restore the system to exactly the state it was in immediately afterversion_idwas committed. The rollback itself is recorded as a new version so the action can be undone.
A failed operation (e.g., adding a duplicate, deleting a non-existent notebook) must not create a version.
Aim for better than O(n) time and space per mutation for the versioning layer. Describe your design choices and their trade-offs.
Constraints
- Up to ~100 000 notebooks and members.
- All operations should have reasonable time complexity; state your analysis.
- Implement in the language of your choice.
Hints
Hint 1
For levels 1–3, a plain dictionary keyed by id gives O(1) reads and writes. The interesting design work is in level 4: think about what the minimum information is that lets you reconstruct any past state without copying the entire store on every mutation.
Hint 2
A change log beats full snapshots. Instead of cloning the whole dictionary on each write, record what each mutation changed: (table, key, before, after). To roll back to version v, find every key that was touched after v and restore its value from the first change to that key after v — that 'before' value is exactly what existed at v.
Hint 3
Immutable records are your best friend here. If Notebook and Member objects cannot be mutated after creation, you can store plain references in your before/after fields without defensive copying. Use frozen dataclasses in Python, data classes in Kotlin, or records in Java. Also think carefully about which operations should be no-ops versus errors, and document those contracts up front.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two distinct parts with very different difficulty levels.
Levels 1–3 are dictionary bookkeeping. A dict[id → object] gives O(1) CRUD. Search is a linear scan with a case-folded substring check. Listing is a sort, O(n log n). Nothing surprising here.
Level 4 is the real design question. The naive path is to deep-copy the entire store on every mutation. With 100k entities that costs O(n) time and memory per write — fine for a toy, unacceptable in an interview. The better structure is a change log.
Change-log design
Each successful mutation appends a Version to a history list. A Version contains a list of Change(table, key, before, after) records. None in before means the key did not exist yet; None in after means the key was deleted.
To roll back to version v:
- Collect every key touched by any version after
v. - For each such key, its value at version
vis thebeforefield of the first change to that key afterv— because nothing modified the key betweenvand that first change. - Apply those restored values and commit a new version recording the before/after pairs of that rollback.
This is correct even when the intervening history contains earlier rollbacks, because every rollback is itself an ordinary version with honest before/after records.
Why make records immutable? If Notebook is a frozen dataclass, the before and after fields in a Change are safe references — callers cannot mutate stored history through a returned object. No defensive copies needed anywhere.
Contract decisions (state these explicitly)
| Situation | Behavior |
|---|---|
add_notebook with duplicate id | Reject, return None |
update_notebook / delete_notebook on missing id | Return None, no version created |
update_notebook with unrecognized field | Raise ValueError |
update_notebook with no effective change | No new version; return current version id |
add_member with duplicate id | Reject, return None |
search_notebooks("") | Returns all notebooks |
list_notebooks with unknown sort_by | Raise ValueError |
rollback to current version | No-op |
rollback to invalid version id | Return None |
Complexity
| Operation | Time | Extra space |
|---|---|---|
| add / update / get / delete / add_member | O(1) | O(1) per version entry |
search_notebooks | O(n · L) | O(m) result |
list_notebooks | O(n log n) | O(n) |
version_history | O(total changes) | output only |
rollback(v) | O(C) where C = changes after v | O(C) |
Total memory for history is O(total changes), not O(n × number of versions).
Python implementation
from dataclasses import dataclass, replace, field
from typing import Optional, List, Dict, Any
@dataclass(frozen=True)
class Notebook:
notebook_id: str
title: str
page_count: int
@dataclass(frozen=True)
class Member:
member_id: str
member_name: str
@dataclass(frozen=True)
class Change:
table: str # "notebooks" or "members"
key: str
before: Any # None => key was absent
after: Any # None => key is deleted
@dataclass
class Version:
version_id: int
description: str
changes: List[Change] = field(default_factory=list)
class NotebookSystem:
_UPDATABLE = {"title", "page_count"}
def __init__(self) -> None:
self._tables: Dict[str, Dict[str, Any]] = {
"notebooks": {},
"members": {},
}
self._history: List[Version] = [Version(0, "init")]
# ── internal helpers ──────────────────────────────────────────
def _apply(self, table: str, key: str, value: Any) -> None:
t = self._tables[table]
if value is None:
t.pop(key, None)
else:
t[key] = value
def _commit(self, description: str, changes: List[Change]) -> int:
for c in changes:
self._apply(c.table, c.key, c.after)
vid = len(self._history)
self._history.append(Version(vid, description, changes))
return vid
@property
def current_version(self) -> int:
return len(self._history) - 1
# ── Level 1: CRUD ─────────────────────────────────────────────
def add_notebook(self, notebook: Notebook) -> Optional[int]:
if notebook.notebook_id in self._tables["notebooks"]:
return None
return self._commit(
f"add notebook {notebook.notebook_id}",
[Change("notebooks", notebook.notebook_id, None, notebook)],
)
def update_notebook(self, notebook_id: str, **fields) -> Optional[int]:
bad = set(fields) - self._UPDATABLE
if bad:
raise ValueError(f"unrecognised fields: {sorted(bad)}")
old = self._tables["notebooks"].get(notebook_id)
if old is None:
return None
new = replace(old, **fields)
if new == old:
return self.current_version # no-op, no new version
return self._commit(
f"update notebook {notebook_id}",
[Change("notebooks", notebook_id, old, new)],
)
def get_notebook(self, notebook_id: str) -> Optional[Notebook]:
return self._tables["notebooks"].get(notebook_id)
def delete_notebook(self, notebook_id: str) -> Optional[int]:
old = self._tables["notebooks"].get(notebook_id)
if old is None:
return None
return self._commit(
f"delete notebook {notebook_id}",
[Change("notebooks", notebook_id, old, None)],
)
# ── Level 2: search & list ────────────────────────────────────
def search_notebooks(self, query: str) -> List[Notebook]:
q = query.strip().lower()
hits = [
nb for nb in self._tables["notebooks"].values()
if q in nb.title.lower()
]
hits.sort(key=lambda nb: (nb.title.lower(), nb.notebook_id))
return hits
def list_notebooks(self, sort_by: str) -> List[Notebook]:
all_nbs = list(self._tables["notebooks"].values())
if sort_by == "title":
all_nbs.sort(key=lambda nb: (nb.title.lower(), nb.notebook_id))
elif sort_by == "page_count":
all_nbs.sort(key=lambda nb: (nb.page_count, nb.notebook_id))
else:
raise ValueError(f"unknown sort_by: {sort_by!r}")
return all_nbs
# ── Level 3: members ──────────────────────────────────────────
def add_member(self, member: Member) -> Optional[int]:
if member.member_id in self._tables["members"]:
return None
return self._commit(
f"add member {member.member_id}",
[Change("members", member.member_id, None, member)],
)
# ── Level 4: versioning & rollback ───────────────────────────
def version_history(self) -> List[Version]:
return list(self._history)
def rollback(self, version_id: int) -> Optional[int]:
if not (0 <= version_id < len(self._history)):
return None
if version_id == self.current_version:
return self.current_version
# For every key touched after version_id, find its value AT version_id.
# That value is the 'before' of the first change to that key after version_id.
first_before: Dict[tuple, Any] = {}
for version in self._history[version_id + 1:]:
for c in version.changes:
coord = (c.table, c.key)
if coord not in first_before:
first_before[coord] = c.before
rollback_changes = [
Change(table, key, self._tables[table].get(key), value)
for (table, key), value in first_before.items()
]
return self._commit(
f"rollback to version {version_id}",
rollback_changes,
)
Common mistakes to avoid
- Full snapshot on every write. Storing a deep copy of the entire store each time works for tiny inputs but breaks at scale. Change logs keep total history memory proportional to the number of individual field changes, not the size of the store.
- Mutable stored objects. If you store plain mutable objects in
before/after, a caller who receives a reference can corrupt history silently. Frozen dataclasses or similar immutable types close this hole. - Creating versions for failed operations. Only successful mutations should increment the version counter. Rejections, no-ops, and validation errors must leave history untouched.
- Destroying history on rollback. Truncating the history list after a rollback makes it impossible to redo or re-rollback. Record the rollback as a new version instead.
Possible follow-up questions
- Periodic checkpoints: if rollback ranges are large, a full snapshot every 1 000 versions bounds rollback time to O(1 000 + C) without changing normal-write complexity.
- Faster search: an inverted index on title tokens drops search from O(n · L) to roughly O(query length + results).
- Concurrent access: the change log is naturally append-only, which makes it straightforward to add reader-writer locking per table if you need thread safety.