Build an In-Memory Meal Catalog with Search and Updates
Data Structure DesignModel answerLast updated
Create a service that stores meal records with auto-incrementing IDs, normalized fields, atomic modifications, and filtered search with multiple sort orders.
Problem
Build an in-memory catalog system for managing meal records. The system must assign sequential IDs, normalize text fields, prevent partial updates on validation failures, and support filtered search with configurable ordering.
Core Requirements
ID Assignment and Field Normalization
- Assign each new meal an integer ID, starting at
1and incrementing by1 - Normalize ingredient and tag lists: remove leading/trailing whitespace, convert to lowercase, eliminate duplicates while maintaining the order of first appearances
- Protect internal state from external mutations by creating independent copies of all input and output collections
Atomic Modification Guarantees
- When updating a meal, either apply all changes or none at all
- If any validation error occurs (negative preparation time, invalid meal ID, unrecognized field), leave the entire meal and all indexes unchanged
Filtered and Sorted Search
- Filter by optional tag (case-insensitive match) and optional maximum preparation time (inclusive)
- Support three sort modes:
"prep_time_asc": order by preparation time ascending, then by ID ascending"prep_time_desc": order by preparation time descending, then by ID ascending"title_asc": order by title alphabetically ascending, then by ID ascending
- Return a list of meal IDs matching the filters in the specified order
Interface
class RecipeService:
def __init__(self):
pass
def create_recipe(self, title: str, ingredients: list[str], tags: list[str], prep_time: int) -> int:
"""Store a new meal and return its assigned ID."""
pass
def get_recipe(self, recipe_id: int) -> dict | None:
"""Retrieve meal data as a dict with keys: 'id', 'title', 'ingredients', 'tags', 'prep_time'.
Returns None if the ID doesn't exist."""
pass
def update_recipe(self, recipe_id: int, updates: dict) -> bool:
"""Modify specified fields ('title', 'ingredients', 'tags', 'prep_time').
Returns True on success, False on any validation failure."""
pass
def delete_recipe(self, recipe_id: int) -> bool:
"""Remove a meal by ID. Returns True if deleted, False if not found."""
pass
def search_recipes(self, tag: str | None = None, max_prep_time: int | None = None,
sort_by: str = "prep_time_asc") -> list[int]:
"""Find meals matching the given criteria, sorted according to sort_by."""
pass
Test Cases
service = RecipeService()
id1 = service.create_recipe("Omelette", ["Eggs", " Cheese ", "eggs"], ["Breakfast", " FAST "], 15)
# id1 == 1
# Stored ingredients: ["eggs", "cheese"]
# Stored tags: ["breakfast", "fast"]
id2 = service.create_recipe("Smoothie", ["banana", "milk"], ["breakfast"], 5)
# id2 == 2
service.search_recipes(tag="breakfast", max_prep_time=20, sort_by="prep_time_asc")
# Returns: [2, 1] (prep_time 5 before 15)
service.update_recipe(1, {"prep_time": -10})
# Returns: False (negative time rejected; meal unchanged)
service.delete_recipe(2)
# Returns: True
service.search_recipes(tag="breakfast")
# Returns: [1]
Constraints
- Preparation time must be non-negative for valid records
- Titles must be non-empty
- At most
2 × 10^4total operations - At most
5,000meals stored simultaneously
Hints
Hint 1
Build a helper function to normalize string lists once and reuse it for both creation and updates.
Hint 2
Use an inverted index mapping each tag to the set of meal IDs that contain it to avoid scanning all meals on every search.
Hint 3
For atomic updates, validate all changes in local variables before modifying any shared state or indexes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem emphasizes clean state management and data integrity over algorithmic complexity. The solution relies on four design choices.
1. Centralized Normalization
Create a single normalization function for both ingredients and tags. It strips whitespace, converts to lowercase, and removes duplicates while preserving first-occurrence order. Building a new list provides the defensive copy automatically.
def _normalize(items) -> list[str]:
seen, result = set(), []
for item in items:
normalized = item.strip().lower()
if normalized and normalized not in seen:
seen.add(normalized)
result.append(normalized)
return result
This ensures ["Eggs", " eggs ", "EGGS"] becomes ["eggs"] consistently.
2. Primary Storage Plus Secondary Index
Maintain two data structures:
_recipes: dict[int, dict]— primary storage mapping meal ID to its full record_tag_index: dict[str, set[int]]— inverted index mapping each tag to IDs containing it
The inverted index allows tag-based searches to examine only relevant meals instead of scanning the entire collection. Without a tag filter, we fall back to scanning all IDs.
3. Validate-Then-Commit Pattern
For atomic updates, separate validation from modification:
Phase 1 (Validation): Build all new values in local variables. Check that the meal exists, all update keys are recognized, and all values are valid. This phase reads state but never writes.
Phase 2 (Commit): Once everything passes validation, update the primary store and adjust the tag index. Since all values are pre-validated, this phase cannot partially fail.
# Validation phase - no state changes
new_title = updates.get("title", rec["title"])
new_tags = _normalize(updates["tags"]) if "tags" in updates else rec["tags"]
# ... validate all fields
# Commit phase - all changes at once
rec["title"] = new_title
rec["tags"] = new_tags
_update_tag_index(recipe_id, old_tags, new_tags)
4. Tuple-Based Sorting
Map each sort mode to a key function that returns a tuple. The ID always appears last as the tiebreaker, ensuring deterministic ordering.
sort_keys = {
"prep_time_asc": lambda rid: (recipes[rid]["prep_time"], rid),
"prep_time_desc": lambda rid: (-recipes[rid]["prep_time"], rid),
"title_asc": lambda rid: (recipes[rid]["title"], rid),
}
Negating prep_time for descending order preserves the ascending ID tiebreaker without reversing the entire list.
Implementation Details
ID Assignment: Increment _next_id only after successful creation. Failed creates don't consume IDs. Deleted IDs are never reused.
Defensive Copies:
- Input lists are rebuilt during normalization
get_recipereturns a new dict with fresh lists, preventing external mutations from corrupting internal state
Index Maintenance: When updating tags, remove the meal ID from old tag buckets and add it to new ones. Delete empty buckets to avoid memory leaks.
Edge Cases:
- Empty or whitespace-only strings after stripping are dropped from lists
- Python treats
boolas a subclass ofint, so explicitly reject boolean prep_time values - Empty update dicts on existing meals succeed as no-ops
- Unknown sort modes raise errors rather than defaulting silently
Complexity Analysis
With k = fields per meal, N = total meals, M = search candidates:
| Operation | Time Complexity | Explanation |
|---|---|---|
create_recipe | O(k) | Normalization and index updates |
get_recipe | O(k) | Copying lists |
update_recipe | O(k_old + k_new) | Index differential update |
delete_recipe | O(k) | Index cleanup |
search_recipes | O(M log M) | M = N without tag filter, or tag bucket size |
Space complexity is O(total fields across all meals) for storage plus the inverted index. With N ≤ 5,000 and at most 20,000 operations, sorting on every query is efficient enough.
Code
from typing import Optional
class RecipeService:
_ALLOWED_UPDATES = {"title", "ingredients", "tags", "prep_time"}
def __init__(self):
self._recipes: dict[int, dict] = {}
self._tag_index: dict[str, set[int]] = {}
self._next_id = 1
@staticmethod
def _normalize(items) -> list[str]:
if not isinstance(items, (list, tuple)):
raise ValueError("expected list")
seen, out = set(), []
for item in items:
if not isinstance(item, str):
raise ValueError("items must be strings")
norm = item.strip().lower()
if norm and norm not in seen:
seen.add(norm)
out.append(norm)
return out
@staticmethod
def _validate_prep_time(prep_time) -> int:
if isinstance(prep_time, bool) or not isinstance(prep_time, int) or prep_time < 0:
raise ValueError("prep_time must be non-negative integer")
return prep_time
def _update_tag_index(self, meal_id: int, old_tags: list[str], new_tags: list[str]):
for tag in old_tags:
if tag not in new_tags:
bucket = self._tag_index.get(tag)
if bucket:
bucket.discard(meal_id)
if not bucket:
del self._tag_index[tag]
for tag in new_tags:
self._tag_index.setdefault(tag, set()).add(meal_id)
def create_recipe(self, title: str, ingredients: list[str],
tags: list[str], prep_time: int) -> int:
if not isinstance(title, str) or not title.strip():
raise ValueError("title required")
norm_ingredients = self._normalize(ingredients)
norm_tags = self._normalize(tags)
prep_time = self._validate_prep_time(prep_time)
meal_id = self._next_id
self._next_id += 1
self._recipes[meal_id] = {
"id": meal_id,
"title": title,
"ingredients": norm_ingredients,
"tags": norm_tags,
"prep_time": prep_time,
}
for tag in norm_tags:
self._tag_index.setdefault(tag, set()).add(meal_id)
return meal_id
def get_recipe(self, recipe_id: int) -> Optional[dict]:
rec = self._recipes.get(recipe_id)
if not rec:
return None
return {
"id": rec["id"],
"title": rec["title"],
"ingredients": list(rec["ingredients"]),
"tags": list(rec["tags"]),
"prep_time": rec["prep_time"],
}
def update_recipe(self, recipe_id: int, updates: dict) -> bool:
rec = self._recipes.get(recipe_id)
if not rec:
return False
# Validation phase
if not all(k in self._ALLOWED_UPDATES for k in updates):
return False
try:
new_title = updates.get("title", rec["title"])
if not isinstance(new_title, str) or not new_title.strip():
return False
new_ingredients = (self._normalize(updates["ingredients"])
if "ingredients" in updates else rec["ingredients"])
new_tags = (self._normalize(updates["tags"])
if "tags" in updates else rec["tags"])
new_prep = (self._validate_prep_time(updates["prep_time"])
if "prep_time" in updates else rec["prep_time"])
except (ValueError, TypeError):
return False
# Commit phase
old_tags = rec["tags"]
rec["title"] = new_title
rec["ingredients"] = new_ingredients
rec["tags"] = new_tags
rec["prep_time"] = new_prep
self._update_tag_index(recipe_id, old_tags, new_tags)
return True
def delete_recipe(self, recipe_id: int) -> bool:
rec = self._recipes.pop(recipe_id, None)
if not rec:
return False
for tag in rec["tags"]:
bucket = self._tag_index.get(tag)
if bucket:
bucket.discard(recipe_id)
if not bucket:
del self._tag_index[tag]
return True
def search_recipes(self, tag: str | None = None,
max_prep_time: int | None = None,
sort_by: str = "prep_time_asc") -> list[int]:
if tag is not None:
norm_tag = tag.strip().lower()
candidates = list(self._tag_index.get(norm_tag, set()))
else:
candidates = list(self._recipes.keys())
if max_prep_time is not None:
candidates = [rid for rid in candidates
if self._recipes[rid]["prep_time"] <= max_prep_time]
sort_keys = {
"prep_time_asc": lambda rid: (self._recipes[rid]["prep_time"], rid),
"prep_time_desc": lambda rid: (-self._recipes[rid]["prep_time"], rid),
"title_asc": lambda rid: (self._recipes[rid]["title"], rid),
}
if sort_by not in sort_keys:
raise ValueError(f"unknown sort mode: {sort_by}")
return sorted(candidates, key=sort_keys[sort_by])
Common Mistakes
- Forgetting defensive copies: Returning direct references to internal lists allows external code to corrupt state
- Partial updates on validation failure: Updating the primary store before validating all fields breaks atomicity
- Case-sensitive tag matching: Forgetting to normalize the search tag parameter causes mismatches
- Leaking empty index buckets: Not deleting empty sets wastes memory over many operations
- Unstable sorts: Omitting the ID tiebreaker makes ordering non-deterministic when other fields match