Building an In-Memory Recipe Store with Search and Versioning
Data Structure DesignModel answerLast updated
Design an in-memory recipe system with CRUD, ingredient lookup, per-user attribution with sorting, and immutable version history that survives deletes.
You are asked to sketch (and, time permitting, code) an in-memory recipe store. No UI and no persistence — the grader cares about API shape, choice of data structures, and how you treat edge cases. There are four progressively harder requirements.
Tier 1 — CRUD. A recipe has a name (the unique key), an ordered list of ingredients, and an ordered list of steps. Support create, read, update, delete.
Tier 2 — Ingredient lookup. Return every currently active recipe that uses a given ingredient.
Tier 3 — Users and ordering. Introduce users. Every mutating call must name the user performing it, and each recipe tracks who touched it last. Provide a listing operation that sorts by a caller-chosen key (name, ingredient count, step count, …) in ascending or descending order.
Tier 4 — Version history. Every create and every update produces an immutable snapshot recording the content, a version number, a timestamp, and the editing user. You must be able to list versions of a recipe and search history by recipe name or by editor. History outlives deletion: even after the active recipe is removed, its versions stay queryable.
State your class/API design, your data structures (including any secondary indexes), complexity per operation, and how you decide corner cases: duplicate or reused names, ingredient normalization, partial updates, deleting then recreating a recipe, unknown users, and invalid sort keys.
Hints
Hint 1
One dictionary holds live recipes and a separate dictionary holds history — never let a delete touch the history structure, or Tier 4 breaks.
Hint 2
Maintain inverted indexes (ingredient → set of names, editor → list of versions) so queries don't scan everything; update them at exactly the three mutation points.
Hint 3
Make snapshots frozen (immutable tuples/dataclasses) so a caller holding a returned reference can't rewrite history.
Hint 4
Decide explicitly whether version numbers reset after delete-and-recreate — continuing the lineage keeps (name, version) a permanent unique key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The whole problem is about keeping several views of the same data consistent. There are four concerns, and each deserves its own structure rather than one big object graph you scan repeatedly:
| Concern | Structure | Why |
|---|---|---|
| Live recipes | dict[name, Recipe] | O(1) create/read/delete |
| Ingredient lookup | dict[ingredient, set[name]] (inverted index) | Tier 2 without scanning all recipes |
| Users | dict[user_id, User] | Validate the actor on every mutation |
| History | dict[name, list[Version]] + dict[user_id, list[Version]] | Tier 4 lookups by name and by editor |
The history structures are deliberately separate from the live store. A delete removes from the recipe dict and the ingredient index only — the history lists are untouched, which is exactly the Tier 4 guarantee.
API sketch
register_user(user_id) -> Usercreate_recipe(actor, name, ingredients, steps) -> Recipeget_recipe(name) -> Recipeupdate_recipe(actor, name, ingredients=None, steps=None) -> Recipe(partial update)delete_recipe(actor, name) -> Nonesearch_by_ingredient(ingredient) -> list[str]list_recipes(sort_key, descending=False) -> list[Recipe]list_versions(name) -> list[Version]search_history(name=None, editor=None) -> list[Version]
Every mutation funnels through one private method that (a) validates the actor, (b) writes the live record, (c) patches the ingredient index, and (d) appends a frozen version. Centralizing it is what makes the indexes provably consistent: there is no path that updates one view without the others.
Immutability
Recipe and Version are frozen dataclasses whose list fields are stored as tuples. A caller who receives a Version cannot mutate the stored snapshot, and nothing internal ever edits a version in place — versions are append-only. That is what "immutable snapshot" means operationally.
Corner cases and the decisions behind them
- Name normalization: trim and collapse internal whitespace. Uniqueness applies only to active recipes. Recreating a previously deleted name is allowed.
- Version lineage: after delete-and-recreate, numbering continues (v1, v2, then v3). One name = one lineage, so
(name, version)is a permanently unique key and history queries by name are unambiguous. The alternative — resetting to v1 — would collide with old snapshots and is a trap worth naming out loud. - Ingredient normalization: trim, collapse whitespace, lowercase, and de-duplicate in first-seen order.
" Olive Oil"equals"olive oil", and search queries go through the same function so they match. Store the normalized form only; keep steps verbatim and ordered. - Partial updates: you may pass ingredients, steps, or both. Passing neither is an error (it would create a meaningless version). Every successful update writes a new version.
- Last modifier:
last_modified_byis written in the same step as the version'seditor, so they can never disagree. - Unknown actor / missing recipe: distinct exception types (
UnknownUserError,RecipeNotFoundError,DuplicateRecipeError). - Time: inject a clock so tests are deterministic; order versions by version number, not timestamp, so equal timestamps don't matter.
- Bad input: an empty name, empty ingredient string, empty step, or a bare string passed where a list is expected all raise
ValueError. An empty ingredient list is legal. Unknown sort keys raiseValueError; ties break by name for stable output.
Complexity
With k = ingredients in a recipe, s = steps, n = active recipes, v = versions of a recipe:
- create/delete: O(k + s) to normalize/copy, plus index updates.
- get: O(1).
- update: O(k_old + k_new + s) — diff old vs new ingredients to patch the index.
- ingredient search: O(m log m) over m matches if you sort output.
- sorted listing: O(n log n).
- versions of one recipe: O(v); history by editor: O(v_e) for that editor.
Space is dominated by history — O(total content across all snapshots) — which is inherent to the requirement. Worth stating: you could store deltas instead, but snapshots are simpler and the trade-off is memory for simplicity.
What strong candidates get right
They separate live state from history, patch indexes only at mutation points, freeze snapshots, and explicitly resolve the ambiguous rules (recreated names, normalization, partial updates) rather than leaving them implicit. Common mistakes: scanning all recipes for ingredient search, letting a delete wipe history, returning references to internal lists, and forgetting to handle the delete-then-recreate version numbering question.