Recipe manager with ingredient search
Build an in-memory recipe book. Each recipe has a name, an ordered list of ingredients and an ordered list of steps. The work comes in two parts; finish part 1 before you start part 2.
Part 1: create, read, update, delete
Implement a RecipeManager class:
-
add_recipe(name, ingredients, steps) -> str: store a new recipe and return its id. Ids are"recipe1","recipe2", ... in creation order, and an id is never reused, even after its recipe is deleted. Return""if the name is blank or another stored recipe already has the same name. Names are compared case-insensitively, ignoring leading and trailing spaces. -
get_recipe(recipe_id) -> Recipe | None: return the recipe (id, name, ingredients, steps) with lists in their original order and spelling, orNoneif the id does not exist. -
update_recipe(recipe_id, name, ingredients, steps) -> bool: replace all three fields. ReturnFalseand change nothing if the id does not exist or the new name belongs to a different recipe. A recipe may keep its own name or change its capitalization. -
delete_recipe(recipe_id) -> bool: remove the recipe;Falseif it does not exist.
Part 2: search
-
search_by_ingredient(ingredient) -> list[str]: ids of recipes that use the ingredient (case-insensitive exact match), oldest first. -
search_by_name(query) -> list[str]: ids of recipes whose name containsquery, case-insensitive, oldest first. -
find_cookable(pantry) -> list[str]: ids of recipes whose every ingredient is inpantry, oldest first. A recipe with no ingredients is always cookable.
Searches will be far more frequent than writes. State the time complexity of each method.
Example
m = RecipeManager()
m.add_recipe("Fried rice", ["rice", "egg", "scallion"], ["cook rice", "stir-fry"]) # "recipe1"
m.add_recipe("Boiled egg", ["egg"], ["boil 9 minutes"]) # "recipe2"
m.add_recipe("FRIED RICE", ["rice"], []) # "" (name taken)
m.search_by_ingredient("Egg") # ["recipe1", "recipe2"]
m.find_cookable(["egg", "rice"]) # ["recipe2"]
m.delete_recipe("recipe1") # True
m.add_recipe("Fried rice", ["rice", "egg"], ["stir-fry"]) # "recipe3"
m.find_cookable(["egg", "rice"]) # ["recipe2", "recipe3"]
Constraints
- Up to 10^5 recipes, up to 50 ingredients and 100 steps per recipe.
- Names and ingredients are non-empty strings of at most 100 characters.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.

