Design an In-Memory Recipe Storage Engine
Data Structure DesignModel answerLast updated
Design and implement an in-memory storage manager supporting CRUD operations, custom identifier parsing, case-insensitive uniqueness, and controlled renames.
Design an in-memory storage manager, RecipeStore, to maintain recipe objects and perform standard CRUD operations under specific constraints.
Each recipe entity comprises:
id: A string identifier formatted as"recipe<n>"(e.g.,"recipe1","recipe2").name: A string representing the name of the recipe.ingredients: A list of strings.steps: A list of strings.
Implement the following public operations:
-
create(name: str, ingredients: List[str], steps: List[str]) -> str- Assigns a sequential string ID starting at
"recipe1","recipe2", etc. IDs must strictly increment and cannot be recycled after deletion. - Enforces unique recipe names in a case-insensitive manner (e.g.,
"Tiramisu"and"tIrAmIsU"conflict). - Preserves the original casing provided during creation.
- Returns the generated recipe ID. If creation fails due to a duplicate name, raise an exception or handle it according to standard API safety patterns.
- Assigns a sequential string ID starting at
-
get(recipe_id: str) -> Optional[Recipe]- Retrieves the recipe matching
recipe_id. - Parses the ID string to extract the integer suffix. If the ID format is invalid or the recipe does not exist, returns
None.
- Retrieves the recipe matching
-
update(recipe_id: str, updated_recipe: Recipe) -> bool- Replaces the attributes of an existing recipe.
- Fails (returns
False) ifrecipe_idis invalid, does not exist, or ifrecipe_id != updated_recipe.id. - Modifying the name is strictly restricted: only case-only changes are permitted (e.g., changing
"Pasta"to"PASTA"is valid, but changing"Pasta"to"Pizza"is invalid). - On a successful update, future
getcalls must reflect the new casing.
-
delete(recipe_id: str) -> bool- Removes the recipe associated with
recipe_id. - Returns
Trueif successfully deleted, orFalseifrecipe_idis invalid or non-existent. - Once deleted, its name is freed, allowing new recipes to reuse that name.
- Removes the recipe associated with
Requirements & Edge Cases
- ID Formatting: Valid IDs consist of the exact string
"recipe"followed by a positive integer in canonical base-10 format without leading zeros (e.g.,"recipe1"is valid;"recipe01","recipe0","recipe-1","Recipe1", and"recipe"are invalid). - Immutability & Encapsulation: Returned objects should not allow consumers to mutate internal data store state directly.
Hints
Hint 1
Use two primary maps: one keyed by the parsed numeric ID to store the entity, and another keyed by the casefolded name mapping to the numeric ID for O(1) duplicate checks.
Hint 2
Validate the ID format cleanly at the boundary by stripping the prefix and ensuring the remainder contains strictly canonical positive decimal digits (no leading zeros).
Hint 3
When updating, verify that the casefolded version of the existing name equals the casefolded version of the new name before applying changes.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The primary goal of this problem is to maintain two consistent indexes while satisfying exact validation invariants:
- Primary Index (
_by_id): Maps an integer IDnto the storedRecipeobject. Storing the numeric value internally simplifies lookups and prevents issues around raw string manipulation. - Name Index (
_id_by_name): Maps a normalized (casefolded) string to its current numeric IDn. This allows $O(1)$ duplicate checks regardless of character case.
Operational Logic:
- ID Parsing: Extract the
"recipe"prefix and inspect the numeric suffix. We ensure the suffix consists only of ASCII decimal digits, contains no leading zeros (unless it were a lone zero, which is also invalid since IDs start at 1), and parses to a positive integer. create: Casefolds the target name. If the normalized key exists in_id_by_name, reject the operation. Otherwise, increment an internal sequence counter, construct the identifier"recipe<n>", and populate both_by_idand_id_by_name.get: Validates the ID, retrieves the item from_by_id, and returns a defensive deep copy so callers cannot mutate stored fields without invokingupdate.update: Ensures the ID format is valid, the recipe exists,updated_recipe.id == recipe_id, and the normalized version ofupdated_recipe.namematches the normalized existing name. If all checks pass, update the stored recipe's fields (including the new casing).delete: Validates the ID and fetches the existing record. Removes the entry from_by_idand purges its entry from_id_by_name.
Python Code
from dataclasses import dataclass
from typing import Dict, List, Optional
@dataclass
class Recipe:
id: str
name: str
ingredients: List[str]
steps: List[str]
class RecipeStore:
_PREFIX = "recipe"
def __init__(self) -> None:
self._next_id: int = 1
self._by_id: Dict[int, Recipe] = {}
self._id_by_name: Dict[str, int] = {} # casefolded_name -> numeric_id
@staticmethod
def _normalize_name(name: str) -> str:
return name.casefold()
@classmethod
def _parse_id(cls, recipe_id: object) -> Optional[int]:
"""Parses a string like 'recipe12' into 12.
Rejects malformed strings, invalid prefixes, and non-canonical numbers.
"""
if not isinstance(recipe_id, str) or not recipe_id.startswith(cls._PREFIX):
return None
suffix = recipe_id[len(cls._PREFIX):]
if not suffix or not (suffix.isascii() and suffix.isdigit()):
return None
# Disallow leading zeros (e.g., 'recipe01', 'recipe0')
if suffix[0] == "0":
return None
return int(suffix)
@staticmethod
def _copy_recipe(r: Recipe) -> Recipe:
return Recipe(
id=r.id,
name=r.name,
ingredients=list(r.ingredients),
steps=list(r.steps),
)
def create(self, name: str, ingredients: List[str], steps: List[str]) -> str:
key = self._normalize_name(name)
if key in self._id_by_name:
raise ValueError(f"Recipe with name '{name}' already exists.")
num_id = self._next_id
self._next_id += 1
str_id = f"{self._PREFIX}{num_id}"
stored_recipe = Recipe(
id=str_id,
name=name,
ingredients=list(ingredients),
steps=list(steps),
)
self._by_id[num_id] = stored_recipe
self._id_by_name[key] = num_id
return str_id
def get(self, recipe_id: str) -> Optional[Recipe]:
num_id = self._parse_id(recipe_id)
if num_id is None:
return None
recipe = self._by_id.get(num_id)
return self._copy_recipe(recipe) if recipe is not None else None
def update(self, recipe_id: str, updated_recipe: Recipe) -> bool:
num_id = self._parse_id(recipe_id)
if num_id is None or updated_recipe is None:
return False
existing = self._by_id.get(num_id)
if existing is None:
return False
# Precondition checks
if updated_recipe.id != recipe_id:
return False
if self._normalize_name(updated_recipe.name) != self._normalize_name(existing.name):
return False # Only case modifications are allowed
# Apply update
self._by_id[num_id] = self._copy_recipe(updated_recipe)
return True
def delete(self, recipe_id: str) -> bool:
num_id = self._parse_id(recipe_id)
if num_id is None:
return False
recipe = self._by_id.get(num_id)
if recipe is None:
return False
key = self._normalize_name(recipe.name)
del self._by_id[num_id]
del self._id_by_name[key]
return True
Complexity Analysis
-
Time Complexity:
create: $O(L + I + S)$, where $L$ is the length ofname, $I$ is the number of ingredients, and $S$ is the number of steps. String normalization takes $O(L)$, and array copying takes $O(I + S)$. Map operations take $O(1)$ average time.get: $O(I + S)$ to create defensive copies of the lists. Index lookup is $O(1)$.update: $O(L + I + S)$ for validation, normalization check, and copying elements.delete: $O(L)$ to compute the casefolded key and remove elements from maps.
-
Space Complexity:
- Total auxiliary space is $O(N \cdot (L + I + S))$, where $N$ is the number of active recipes stored across
_by_idand_id_by_name.
- Total auxiliary space is $O(N \cdot (L + I + S))$, where $N$ is the number of active recipes stored across