Hierarchical Recipe and Pantry Fulfillment Service
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Problem Statement
Implement a thread-safe in-memory kitchen management service (RecipeService) that tracks raw pantry ingredients, potentially nested dish recipes, and all-or-nothing customer orders.
To prevent name collisions when a raw pantry item and a prepared dish share the same string identifier, ingredient references use two distinct immutable wrapper types (Ref = Union[Raw, Dish]):
Raw(name: str)— points tonamein the raw pantry inventory.Dish(name: str)— points to another stored recipe namedname.Recipe(name: str, prep_minutes: int, ingredients: Tuple[Tuple[Ref, int], ...])— immutable record returned when inspecting a stored recipe.
Implement RecipeService(max_quantity: int = 2**63 - 1) with the following operations:
__init__(max_quantity: int = 2**63 - 1) -> None: Initializes an empty service wheremax_quantitybounds every ingredient count, pantry stock balance, and expanded raw requirement. RaisesValueErrorifmax_quantityis not an integer>= 1(boolvalues such asTrueare never accepted as integers anywhere in the service).add_recipe(name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: Validates and stores a new recipe.- Raises
TypeErrorifingredientsis not adictor any key is neitherRawnorDish. - Raises
ValueErrorifnameis not a non-emptystr,prep_minutesis not an integer>= 0,ingredientsis empty, any referencedRaw/Dishhas an empty or non-strname, any quantity is not an integer in1..max_quantity,nameis already stored, or adding the recipe would close a direct or indirect dependency cycle among stored recipes. - Forward references (
Dishentries naming recipes that have not been added yet) are allowed on write. - On any exception, stored state remains untouched. Mutating the caller's
ingredientsdictionary afteradd_recipereturns must not alter the stored recipe.
- Raises
replace_recipe(name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: Replaces an existing recipe under the exact same validation and cycle-rejection rules asadd_recipe, raisingKeyErrorifnameis not currently stored.add_supply(name: str, count: int) -> None: Addscountunits of raw pantry itemname. RaisesValueErrorifnameis not a non-emptystr,countis not an integer>= 1, or the updated balance would exceedmax_quantity.place_order(name: str) -> bool: Attempts to prepare one serving of recipenameatomically. NestedDishrequirements multiply along dependency chains and sum across multiple paths reaching the sameRawitem. ReturnsTrueand deducts all required raw quantities together ifnameexists, every reachableDishis defined, no cycle exists, no intermediate or final raw requirement exceedsmax_quantity, and every required raw item hasstock >= required; otherwise returnsFalseand leaves all stock counts unchanged.get_recipe(name: str) -> Optional[Recipe]: Returns the immutableRecipeforname, orNoneif not found.stock(name: str) -> int: Returns the available pantry count of raw itemname(0if never supplied).inventory() -> Dict[str, int]: Returns a newly allocated dictionary of all supplied raw items (including those depleted to0) sorted ascending by item name.recipes_with_prep_time_above(threshold: int) -> List[str]: Returns a sorted list of recipe names whose own storedprep_minutesis strictly greater thanthreshold(>), without adding nested sub-recipe times.raw_requirements(name: str) -> Optional[Dict[str, int]]: Returns a newly allocated name-sorted dictionary of raw units required for one serving ofnameregardless of current pantry stock, orNoneifnamecannot be expanded (unknown recipe, missing nestedDish, cycle, or overmax_quantity).
Examples
Example 1
svc = RecipeService()
svc.add_recipe("broth", 45, {Raw("kelp"): 2, Raw("miso"): 3})
svc.add_recipe("tare", 15, {Raw("soy"): 4, Raw("ginger"): 1})
svc.add_recipe("ramen", 10, {Dish("broth"): 2, Dish("tare"): 1, Raw("noodles"): 2})
svc.raw_requirements("ramen")
# -> {"ginger": 1, "kelp": 4, "miso": 6, "noodles": 2, "soy": 4}
svc.recipes_with_prep_time_above(10)
# -> ["broth", "tare"]
svc.add_supply("kelp", 4)
svc.add_supply("miso", 6)
svc.add_supply("noodles", 2)
svc.add_supply("soy", 4)
svc.place_order("ramen") # -> False (ginger stock is 0; no other item is deducted)
svc.add_supply("ginger", 1)
svc.place_order("ramen") # -> True
svc.inventory()
# -> {"ginger": 0, "kelp": 0, "miso": 0, "noodles": 0, "soy": 0}
Explanation: One ramen scales broth by 2 (4 kelp, 6 miso), adds 1 tare (4 soy, 1 ginger), and adds 2 noodles. Filtering above 10 minutes checks only each recipe's own stored prep_minutes, so ramen (10) is excluded. The first order fails cleanly without touching pantry stock because ginger is missing; once 1 unit of ginger is added, the second order deducts every ingredient atomically.
Example 2
svc = RecipeService()
svc.add_recipe("bento", 8, {Dish("dumpling"): 3, Dish("salad"): 2})
svc.raw_requirements("bento") # -> None (dumpling and salad are not defined yet)
svc.add_recipe("glaze", 6, {Raw("sesame"): 2})
svc.add_recipe("dumpling", 20, {Raw("wrapper"): 1, Dish("glaze"): 1})
svc.add_recipe("salad", 5, {Raw("greens"): 2, Dish("glaze"): 2})
svc.raw_requirements("bento")
# -> {"greens": 4, "sesame": 14, "wrapper": 3}
svc.replace_recipe("glaze", 6, {Dish("bento"): 1})
# -> raises ValueError (glaze -> bento -> dumpling -> glaze forms a cycle)
Explanation: Forward references are accepted when bento is registered, though bento cannot be expanded until dumpling, salad, and glaze exist. Once defined, sesame is reached along two paths—3 * 1 * 2 = 6 via dumpling and 2 * 2 * 2 = 8 via salad—summing to 14 units. Attempting to point glaze back at bento raises ValueError and leaves glaze unchanged.
Constraints
max_quantityis an integer>= 1(defaults to2**63 - 1).- Recipe names and raw ingredient names are non-empty strings in separate namespaces (
Raw("x")vsDish("x")). prep_minutesis an integer>= 0; every ingredient quantity andadd_supplycount is an integer in1..max_quantity(boolis rejected).- Returned recipes and query results must not allow callers to mutate internal service state.
- All public methods must be safe under concurrent multi-threaded access.
Step-by-step walkthrough
Pin down the contract and edge rules
Before writing any class definitions, map every boundary case to a crisp rule so callers and unit tests never have to guess:
Design aspect Contract in RecipeServiceCan a dish and a raw pantry item share the same string? Yes. They occupy separate namespaces because every ingredient key is wrapped in Raw("x")orDish("x"), never a barestr.How are duplicate recipe names handled? add_reciperaisesValueError;replace_recipeoverwrites an existing recipe (and raisesKeyErrorif absent).Are forward references permitted? Yes. A recipe may reference a Dishthat has not been added yet; expanding or ordering it simply fails until that sub-recipe exists.When are dependency cycles caught? Eagerly inside add_recipeandreplace_recipe, guaranteeing the stored graph is always loop-free.Which numeric values are valid? Quantities, supply increments, and expanded totals must be intvalues (neverbool) in1..max_quantity.prep_minutesis anint >= 0.What makes place_orderatomic?Either Trueis returned and every required raw count is subtracted together, orFalseis returned and zero counts change.How does recipes_with_prep_time_abovefilter?Strict >against each recipe's own storedprep_minutes(nested sub-recipe times are not summed), returning sorted names.Can callers mutate internal records via getters? No. Stored Recipeobjects are frozen and dictionary/list getters return fresh copies.A single
threading.Lockguards all reads and writes so concurrent threads observe consistent state.Separate raw items from nested dishes with immutable types
If ingredient maps used bare strings like
{"glaze": 1}, the service could not tell whether"glaze"refers to one bottle of bottled glaze from raw stock or one batch of the"glaze"sub-recipe. Wrapping names in two small frozen dataclasses encodes the namespace directly in the type:Raw("glaze")andDish("glaze")hash and compare as distinct keys even though both wrap"glaze", so a recipe can use both simultaneously.- Marking
Raw,Dish, andRecipewith@dataclass(frozen=True)makes them immutable (reassigning any field raisesFrozenInstanceError), and storing ingredients as an immutabletupleof(ref, quantity)pairs letsget_recipereturn aRecipedirectly without defensive copying. - Because
boolinherits fromintin Python (isinstance(True, int)isTrue), helper_is_intexplicitly rejects booleans soTruenever sneaks through as1.
from typing import Dict, List, Optional, Tuple, Union from dataclasses import dataclass import threading @dataclass(frozen=True) class Raw: """Reference to a raw ingredient that lives in the supply (inventory).""" name: str @dataclass(frozen=True) class Dish: """Reference to another recipe, used as an ingredient.""" name: str Ref = Union[Raw, Dish] @dataclass(frozen=True) class Recipe: """A stored recipe. Frozen, and ingredients is a tuple, so callers cannot change it.""" name: str prep_minutes: int ingredients: Tuple[Tuple[Ref, int], ...] class _InvalidOrder(Exception): """Internal signal: the recipe cannot be expanded (missing Dish, cycle, or over max_quantity).""" def _is_name(value) -> bool: return isinstance(value, str) and value != "" def _is_int(value) -> bool: # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we reject booleans explicitly to stop True from counting as 1. return isinstance(value, int) and not isinstance(value, bool)Validate inputs before mutating recipes or stock
Every write method follows validate first, mutate once.
_build_recipevalidates types and bounds and snapshots the caller'singredientsdictionary into a tuple before acquiringself._lock— so if the caller edits their dictionary later, the storedRecipecannot change.add_supplyenforcescount >= 1and checksnew_count <= self._max_quantitybefore updating_stock, keeping every stock entry inside0..max_quantity.class RecipeService: def __init__(self, max_quantity: int = 2**63 - 1) -> None: if not _is_int(max_quantity) or max_quantity < 1: raise ValueError("max_quantity must be an integer >= 1") self._max_quantity = max_quantity # _recipes maps recipe name -> immutable Recipe, e.g. # {"broth": Recipe("broth", 45, ((Raw("kelp"), 2), (Raw("miso"), 3)))} self._recipes: Dict[str, Recipe] = {} # _stock maps raw ingredient name -> available units, e.g. {"kelp": 4, "miso": 6} self._stock: Dict[str, int] = {} # Single mutex lock serializing reads and writes so orders check-and-decrement atomically self._lock = threading.Lock() def add_recipe(self, name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: # Validate and freeze the caller's input before acquiring the lock recipe = self._build_recipe(name, prep_minutes, ingredients) with self._lock: if name in self._recipes: raise ValueError(f"recipe {name!r} already exists; use replace_recipe") self._store(recipe) def replace_recipe(self, name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: recipe = self._build_recipe(name, prep_minutes, ingredients) with self._lock: if name not in self._recipes: raise KeyError(name) self._store(recipe) def add_supply(self, name: str, count: int) -> None: if not _is_name(name): raise ValueError("ingredient name must be a non-empty string") if not _is_int(count) or count < 1: raise ValueError("count must be an integer >= 1") with self._lock: new_count = self._stock.get(name, 0) + count if new_count > self._max_quantity: raise ValueError(f"stock of {name!r} would exceed max_quantity") self._stock[name] = new_count def _build_recipe(self, name, prep_minutes, ingredients) -> Recipe: """Validate the input and copy it into an immutable Recipe.""" if not _is_name(name): raise ValueError("recipe name must be a non-empty string") if not _is_int(prep_minutes) or prep_minutes < 0: raise ValueError("prep_minutes must be an integer >= 0") if not isinstance(ingredients, dict): raise TypeError("ingredients must be a dict {Raw(...) or Dish(...): quantity}") if len(ingredients) == 0: raise ValueError("a recipe needs at least one ingredient") # Copy (ref, quantity) pairs into an immutable tuple so later edits to the caller's dict are ignored pairs: List[Tuple[Ref, int]] = [] for ref, quantity in ingredients.items(): if not isinstance(ref, (Raw, Dish)): raise TypeError(f"ingredient {ref!r} must be Raw(name) or Dish(name)") if not _is_name(ref.name): raise ValueError("ingredient names must be non-empty strings") if not _is_int(quantity) or quantity < 1 or quantity > self._max_quantity: raise ValueError(f"quantity of {ref!r} must be an integer in 1..max_quantity") pairs.append((ref, quantity)) return Recipe(name, prep_minutes, tuple(pairs))Reject dependency cycles when storing a recipe
Stored recipes form a directed acyclic graph (DAG) — a network of one-way dependency arrows with zero loops, where
bento -> dumplingmeans "bentorequiresDish('dumpling')". A loop such asglaze -> bento -> dumpling -> glazeorloop -> loopwould make expansion infinite.Because every previously stored recipe passed cycle checking,
self._recipesis already acyclic. Thus, inserting or replacingnamecan only close a cycle that starts atname's newDishreferences and reachesnameagain:Stored recipes: bento ---> dumpling ---> glaze Attempt replace_recipe("glaze", 6, {Dish("bento"): 1}): seed stack with glaze's new Dish targets: [bento] pop bento -> follow stored edge to dumpling -> follow stored edge to glaze == target name! Cycle glaze -> bento -> dumpling -> glaze caught -> raise ValueError, keep old glaze.Two details let
_creates_cyclehandle replacements and forward references effortlessly: - Checkingcurrent == namebefore readingself._recipes[name]ensures we never traversename's old edges during areplace_recipecall. - Skippingcurrent not in self._recipestreats not-yet-defined forward references as harmless leaf nodes.def _store(self, recipe: Recipe) -> None: """Insert or overwrite under the lock, unless it would close a cycle.""" if self._creates_cycle(recipe.name, recipe.ingredients): raise ValueError(f"recipe {recipe.name!r} would create a dependency cycle") self._recipes[recipe.name] = recipe def _creates_cycle(self, name, ingredients) -> bool: """Return True if any Dish ingredient in `ingredients` can reach `name` via stored recipes.""" # Because self._recipes is already acyclic, any newly formed cycle must pass through `name`. # stack holds recipe names still to explore; seen avoids revisiting shared sub-recipes. stack: List[str] = [] for ref, _ in ingredients: if isinstance(ref, Dish): stack.append(ref.name) seen = set() while stack: current = stack.pop() if current == name: # Reached `name` again (including a direct self-loop `name -> name`): cycle found return True if current in seen or current not in self._recipes: # Undefined recipes are allowed forward references, so treat them as dead ends here continue seen.add(current) for ref, _ in self._recipes[current].ingredients: if isinstance(ref, Dish): stack.append(ref.name) return FalseFlatten nested recipes with memoized DFS
Fulfilling an order requires flattening a dish's dependency graph into one dictionary of total raw quantities. Quantities multiply down a chain and add across distinct paths reaching the same raw item (as in Example 2):
bento / \ x3 / \ x2 v v dumpling salad / \ / \ x1 / x1 \ x2 / x2 \ v v v v [wrapper] glaze [greens] | | x2 v [sesame] needs(glaze) = {sesame: 2} <-- expanded once, cached in memo needs(dumpling) = {wrapper: 1, sesame: 1 * 2 = 2} needs(salad) = {greens: 2, sesame: 2 * 2 = 4} needs(bento) = 3 * dumpling + 2 * salad = {greens: 4, sesame: 3*2 + 2*4 = 14, wrapper: 3}We walk the graph with depth-first search (DFS) — expanding sub-recipes before scaling and merging their raw dictionaries — backed by three safeguards: - Memoization (
memo) caches each sub-recipe's raw totals for the duration of the expansion so shared sub-recipes likeglazeare computed once instead of re-walked along every path. - Active-path set (visiting) tracks recipes currently open on the call stack, distinguishing a true cycle (name in visiting) from a benign diamond reuse (name in memo). - Capped addition (_add_capped) verifiesnew_total <= self._max_quantityon every partial sum so runaway multipliers abort cleanly with_InvalidOrder.def _expand( self, name: str, memo: Dict[str, Dict[str, int]], visiting: set, ) -> Dict[str, int]: """Compute total raw units required for one serving of `name`.""" # memo maps finished recipe_name -> {"sesame": 2, ...} so shared sub-recipes expand only once if name in memo: return memo[name] # visiting holds recipe names on the current recursion path; seeing one again means a cycle if name in visiting: raise _InvalidOrder(f"cycle through {name!r}") recipe = self._recipes.get(name) if recipe is None: raise _InvalidOrder(f"unknown recipe {name!r}") visiting.add(name) totals: Dict[str, int] = {} for ref, quantity in recipe.ingredients: if isinstance(ref, Raw): self._add_capped(totals, ref.name, quantity) else: sub_totals = self._expand(ref.name, memo, visiting) for raw_name, per_serving in sub_totals.items(): scaled_amount = quantity * per_serving self._add_capped(totals, raw_name, scaled_amount) visiting.discard(name) memo[name] = totals return totals def _add_capped(self, totals: Dict[str, int], raw_name: str, amount: int) -> None: # Enforce max_quantity on every partial sum so huge nested multipliers fail cleanly new_total = totals.get(raw_name, 0) + amount if new_total > self._max_quantity: raise _InvalidOrder(f"{raw_name!r} needs more than max_quantity") totals[raw_name] = new_totalExecute check-and-deduct atomically under the lock
An order is atomic when callers observe either every required raw count deducted together or zero pantry counts modified. That requires both strict three-phase ordering and a mutex lock (a mutual-exclusion lock allowing only one thread inside the critical section at a time):
- Expand
nameintoneededwithout touching_stock. Unknown recipes, missing forward-referenced dishes, andmax_quantityoverflows raise_InvalidOrderand returnFalse. - Verify
available >= amountfor every entry inneeded. In Example 1, whenramenhas enoughkelp,miso,noodles, andsoybut0ginger, returningFalseduring this check loop leaves the other four ingredients untouched. - Deduct every amount from
self._stockand returnTrue.
Holding
self._lockacross all three phases stops two concurrentplace_order("latte")threads (each needing2beanswhenstock["beans"] == 2) from interleaving:Without lock (BUG — oversells stock): Thread 1 checks beans >= 2 (sees 2 -> OK) Thread 2 checks beans >= 2 (sees 2 -> OK) Thread 1 subtracts 2 (beans becomes 0) Thread 2 subtracts 2 (beans becomes -2!) With self._lock around all three phases: Thread 1 locks -> expands -> sees 2 -> deducts 2 (beans = 0) -> unlocks -> True Thread 2 locks -> expands -> sees 0 < 2 -> changes nothing -> unlocks -> FalseKeeping
_expandinside the lock also prevents a concurrentreplace_recipefrom swapping a sub-recipe's ingredients mid-order.def place_order(self, name: str) -> bool: # Run expansion, stock check, and stock subtraction inside one critical section # so neither a concurrent replace_recipe nor another place_order can interleave. with self._lock: # Phase 1: flatten all nested recipes into raw ingredient totals try: needed = self._expand(name, {}, set()) except _InvalidOrder: return False # Phase 2: verify every required raw ingredient has enough stock before changing anything for raw_name, amount in needed.items(): available = self._stock.get(raw_name, 0) if available < amount: return False # Phase 3: all checks passed, so commit every subtraction atomically for raw_name, amount in needed.items(): self._stock[raw_name] -= amount return True- Expand
Return sorted, mutation-safe views from read methods
All query methods acquire
self._lockfor a consistent view and return either frozen objects or defensive copies (newly allocated containers that callers can edit without corrupting internal state):get_recipereturns the storedRecipedirectly becauseRecipe, itsingredientstuple, and everyRaw/Dishelement are frozen.inventoryandraw_requirementsallocate new dictionaries with keys sorted alphabetically.recipes_with_prep_time_abovecomparesrecipe.prep_minutes > threshold(strict>, ignoring nested sub-recipe prep times) and returns sorted names.
def get_recipe(self, name: str) -> Optional[Recipe]: with self._lock: # Recipe and its nested tuples/refs are frozen, so returning it directly is safe return self._recipes.get(name) def stock(self, name: str) -> int: with self._lock: return self._stock.get(name, 0) def inventory(self) -> Dict[str, int]: with self._lock: # Build a brand-new sorted dict so caller edits cannot mutate self._stock result: Dict[str, int] = {} for raw_name in sorted(self._stock): result[raw_name] = self._stock[raw_name] return result def recipes_with_prep_time_above(self, threshold: int) -> List[str]: with self._lock: names: List[str] = [] for recipe in self._recipes.values(): # Strict '>' on the recipe's own stored prep_minutes (nested recipes are not summed) if recipe.prep_minutes > threshold: names.append(recipe.name) names.sort() return names def raw_requirements(self, name: str) -> Optional[Dict[str, int]]: with self._lock: try: needed = self._expand(name, {}, set()) except _InvalidOrder: return None result: Dict[str, int] = {} for raw_name in sorted(needed): result[raw_name] = needed[raw_name] return resultFull solution
Combining the immutable reference types, validated writes, cycle-checked storage, memoized expansion, locked fulfillment, and defensive getters yields the complete
RecipeService.from typing import Dict, List, Optional, Tuple, Union from dataclasses import dataclass import threading @dataclass(frozen=True) class Raw: """Reference to a raw ingredient that lives in the supply (inventory).""" name: str @dataclass(frozen=True) class Dish: """Reference to another recipe, used as an ingredient.""" name: str Ref = Union[Raw, Dish] @dataclass(frozen=True) class Recipe: """A stored recipe. Frozen, and ingredients is a tuple, so callers cannot change it.""" name: str prep_minutes: int ingredients: Tuple[Tuple[Ref, int], ...] class _InvalidOrder(Exception): """Internal signal: the recipe cannot be expanded (missing Dish, cycle, or over max_quantity).""" def _is_name(value) -> bool: return isinstance(value, str) and value != "" def _is_int(value) -> bool: # In Python, bool is a subclass of int (isinstance(True, int) is True), # so we reject booleans explicitly to stop True from counting as 1. return isinstance(value, int) and not isinstance(value, bool) class RecipeService: """Recipes, raw supply, and atomic orders. One lock guards all shared state.""" def __init__(self, max_quantity: int = 2**63 - 1) -> None: if not _is_int(max_quantity) or max_quantity < 1: raise ValueError("max_quantity must be an integer >= 1") self._max_quantity = max_quantity # _recipes maps recipe name -> immutable Recipe, e.g. # {"broth": Recipe("broth", 45, ((Raw("kelp"), 2), (Raw("miso"), 3)))} self._recipes: Dict[str, Recipe] = {} # _stock maps raw ingredient name -> available units, e.g. {"kelp": 4, "miso": 6} self._stock: Dict[str, int] = {} # Single mutex lock serializing reads and writes so orders check-and-decrement atomically self._lock = threading.Lock() # ---------- writes ---------- def add_recipe(self, name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: # Validate and freeze the caller's input before acquiring the lock recipe = self._build_recipe(name, prep_minutes, ingredients) with self._lock: if name in self._recipes: raise ValueError(f"recipe {name!r} already exists; use replace_recipe") self._store(recipe) def replace_recipe(self, name: str, prep_minutes: int, ingredients: Dict[Ref, int]) -> None: recipe = self._build_recipe(name, prep_minutes, ingredients) with self._lock: if name not in self._recipes: raise KeyError(name) self._store(recipe) def add_supply(self, name: str, count: int) -> None: if not _is_name(name): raise ValueError("ingredient name must be a non-empty string") if not _is_int(count) or count < 1: raise ValueError("count must be an integer >= 1") with self._lock: new_count = self._stock.get(name, 0) + count if new_count > self._max_quantity: raise ValueError(f"stock of {name!r} would exceed max_quantity") self._stock[name] = new_count def place_order(self, name: str) -> bool: # Run expansion, stock check, and stock subtraction inside one critical section # so neither a concurrent replace_recipe nor another place_order can interleave. with self._lock: # Phase 1: flatten all nested recipes into raw ingredient totals try: needed = self._expand(name, {}, set()) except _InvalidOrder: return False # Phase 2: verify every required raw ingredient has enough stock before changing anything for raw_name, amount in needed.items(): available = self._stock.get(raw_name, 0) if available < amount: return False # Phase 3: all checks passed, so commit every subtraction atomically for raw_name, amount in needed.items(): self._stock[raw_name] -= amount return True # ---------- reads ---------- def get_recipe(self, name: str) -> Optional[Recipe]: with self._lock: # Recipe and its nested tuples/refs are frozen, so returning it directly is safe return self._recipes.get(name) def stock(self, name: str) -> int: with self._lock: return self._stock.get(name, 0) def inventory(self) -> Dict[str, int]: with self._lock: # Build a brand-new sorted dict so caller edits cannot mutate self._stock result: Dict[str, int] = {} for raw_name in sorted(self._stock): result[raw_name] = self._stock[raw_name] return result def recipes_with_prep_time_above(self, threshold: int) -> List[str]: with self._lock: names: List[str] = [] for recipe in self._recipes.values(): # Strict '>' on the recipe's own stored prep_minutes (nested recipes are not summed) if recipe.prep_minutes > threshold: names.append(recipe.name) names.sort() return names def raw_requirements(self, name: str) -> Optional[Dict[str, int]]: with self._lock: try: needed = self._expand(name, {}, set()) except _InvalidOrder: return None result: Dict[str, int] = {} for raw_name in sorted(needed): result[raw_name] = needed[raw_name] return result # ---------- helpers ---------- def _build_recipe(self, name, prep_minutes, ingredients) -> Recipe: """Validate the input and copy it into an immutable Recipe.""" if not _is_name(name): raise ValueError("recipe name must be a non-empty string") if not _is_int(prep_minutes) or prep_minutes < 0: raise ValueError("prep_minutes must be an integer >= 0") if not isinstance(ingredients, dict): raise TypeError("ingredients must be a dict {Raw(...) or Dish(...): quantity}") if len(ingredients) == 0: raise ValueError("a recipe needs at least one ingredient") # Copy (ref, quantity) pairs into an immutable tuple so later edits to the caller's dict are ignored pairs: List[Tuple[Ref, int]] = [] for ref, quantity in ingredients.items(): if not isinstance(ref, (Raw, Dish)): raise TypeError(f"ingredient {ref!r} must be Raw(name) or Dish(name)") if not _is_name(ref.name): raise ValueError("ingredient names must be non-empty strings") if not _is_int(quantity) or quantity < 1 or quantity > self._max_quantity: raise ValueError(f"quantity of {ref!r} must be an integer in 1..max_quantity") pairs.append((ref, quantity)) return Recipe(name, prep_minutes, tuple(pairs)) def _store(self, recipe: Recipe) -> None: """Insert or overwrite under the lock, unless it would close a cycle.""" if self._creates_cycle(recipe.name, recipe.ingredients): raise ValueError(f"recipe {recipe.name!r} would create a dependency cycle") self._recipes[recipe.name] = recipe def _creates_cycle(self, name, ingredients) -> bool: """Return True if any Dish ingredient in `ingredients` can reach `name` via stored recipes.""" # Because self._recipes is already acyclic, any newly formed cycle must pass through `name`. # stack holds recipe names still to explore; seen avoids revisiting shared sub-recipes. stack: List[str] = [] for ref, _ in ingredients: if isinstance(ref, Dish): stack.append(ref.name) seen = set() while stack: current = stack.pop() if current == name: # Reached `name` again (including a direct self-loop `name -> name`): cycle found return True if current in seen or current not in self._recipes: # Undefined recipes are allowed forward references, so treat them as dead ends here continue seen.add(current) for ref, _ in self._recipes[current].ingredients: if isinstance(ref, Dish): stack.append(ref.name) return False def _expand( self, name: str, memo: Dict[str, Dict[str, int]], visiting: set, ) -> Dict[str, int]: """Compute total raw units required for one serving of `name`.""" # memo maps finished recipe_name -> {"sesame": 2, ...} so shared sub-recipes expand only once if name in memo: return memo[name] # visiting holds recipe names on the current recursion path; seeing one again means a cycle if name in visiting: raise _InvalidOrder(f"cycle through {name!r}") recipe = self._recipes.get(name) if recipe is None: raise _InvalidOrder(f"unknown recipe {name!r}") visiting.add(name) totals: Dict[str, int] = {} for ref, quantity in recipe.ingredients: if isinstance(ref, Raw): self._add_capped(totals, ref.name, quantity) else: sub_totals = self._expand(ref.name, memo, visiting) for raw_name, per_serving in sub_totals.items(): scaled_amount = quantity * per_serving self._add_capped(totals, raw_name, scaled_amount) visiting.discard(name) memo[name] = totals return totals def _add_capped(self, totals: Dict[str, int], raw_name: str, amount: int) -> None: # Enforce max_quantity on every partial sum so huge nested multipliers fail cleanly new_total = totals.get(raw_name, 0) + amount if new_total > self._max_quantity: raise _InvalidOrder(f"{raw_name!r} needs more than max_quantity") totals[raw_name] = new_total✅ Submit now — all tests should pass.
Intuition & how it works
Picture RecipeService as a head chef working from a laminated recipe binder and a locked pantry ledger. When an order arrives for a multi-part meal, the chef never grabs ingredients off the shelves midway through reading the recipe — instead, they flatten the entire nested dish hierarchy onto a single raw-ingredient tally sheet, verify under one kitchen lock that every item on the tally sheet is available, and deduct the entire tally at once.
A naive implementation stumbles on three fronts. First, bare string keys cannot tell a raw pantry bottle named "glaze" apart from a homemade sub-recipe named "glaze". Second, expanding nested dishes without memoization (caching each sub-recipe's flattened result so shared sub-recipes are not recomputed) re-walks diamond dependencies repeatedly and blows up to exponential time on deep menus. Third, deducting stock as you traverse — or checking stock outside a mutex lock (a synchronization primitive letting only one thread enter a critical section at a time) — lets failed orders partially drain the pantry and lets concurrent orders drive stock below zero.
Trace Example 2 where glaze needs 2 sesame, dumpling needs 1 wrapper + 1 glaze, salad needs 2 greens + 2 glaze, and bento needs 3 dumpling + 2 salad:
1. Typed immutable storage: Raw items use Raw("wrapper") while sub-recipes use Dish("glaze"), frozen inside Recipe tuples so callers cannot mutate them. Cycles are rejected on write so stored recipes always form a directed acyclic graph (DAG) — a network of one-way dependencies with no loops.
2. Memoized expansion: Calling place_order("bento") acquires self._lock and runs depth-first search (DFS) (expanding sub-recipes down to raw items before combining them). glaze expands once to {"sesame": 2} and is cached in memo; dumpling scales that to {"sesame": 2, "wrapper": 1}, salad reuses memo["glaze"] to get {"greens": 2, "sesame": 4}, and bento combines 3 * dumpling + 2 * salad into {"greens": 4, "sesame": 14, "wrapper": 3}.
3. Atomic check-then-deduct: An operation is atomic when callers observe either all of its updates or none of them. With 4 greens, 3 wrapper, and 13 sesame in stock, the check loop sees 13 < 14 for sesame and returns False without touching greens or wrapper; once 1 more sesame is supplied (14 total), all checks pass and the deduction loop decrements all three counts to 0 before releasing the lock.
Complexity
Let V be the number of recipes reachable from the target dish, E be the total ingredient links across those reachable recipes, and K be the number of distinct raw ingredients they reference.
place_orderandraw_requirements— O(E * K) time, O(V * K) space: Becausememocaches each reachable sub-recipe's raw dictionary, each of theVrecipes expands once, and each of theEedges merges at mostKraw entries into its parent dictionary. Verifying and deducting stock takesO(K)hash-map lookups, andraw_requirementsaddsO(K log K)to sort theKraw names. Space isO(V * K)for up toVcached dictionaries of size at mostK, plusO(V)call-stack depth.- Why memoization matters in numbers: In a 30-level diamond chain where
r_iusesDish("a_i")andDish("b_i")and both point toDish("r_{i+1}"), unmemoized recursion walks2^30 = 1,073,741,824paths, whereas memoization visits each of the91recipes once. add_recipeandreplace_recipe— O(I + V' + E') time, O(I + V') space: Validating and freezingIingredient pairs costsO(I), and_creates_cycleexplores at mostV'reachable recipes andE'edges once using aseenset of sizeO(V').add_supply,stock, andget_recipe— O(1) average time, O(1) extra space: Each performs a constant number of dictionary operations underself._lock.inventory— O(S log S) time, O(S) space: Allocates a fresh dictionary over allSsupplied raw items in sorted order.recipes_with_prep_time_above— O(N + M log M) time, O(M) space: Scans allNstored recipes once and sorts theMmatching names.
Edge cases
- Exact pantry balance: Fulfilling an order with zero units to spare leaves the raw key in
_stockmapped to0rather than removing the entry. - Unsupplied raw item:
self._stock.get(raw_name, 0)treats never-supplied ingredients as0, causing orders needing them to returnFalsecleanly. - Forward references:
bento -> Dish("dumpling")can be stored beforedumplingexists;place_order("bento")returnsFalseandraw_requirements("bento")returnsNoneuntildumplingis added. - Direct, indirect, and replacement cycles:
loop -> loop,x -> y -> z -> x, and replacingglazeto depend onbentoall raiseValueErrorand preserve prior state. - Updating a shared sub-recipe:
replace_recipeimmediately affects futureplace_orderandraw_requirementscalls without altering already-completed orders. - Shared name across namespaces:
Raw("glaze")andDish("glaze")remain distinct keys and can appear together in one recipe. - Malformed inputs:
0, negative numbers,True/Falsebooleans, floats, strings as counts, empty names, and empty ingredient dicts raiseValueErrororTypeErrorbefore touching state. max_quantitycap: Totals equal tomax_quantitysucceed when stocked, whereasmax_quantity + 1aborts cleanly via_InvalidOrder.- Deep linear chains: Python recursion hits
RecursionErrorpast ~1,000 nested levels (still before any stock mutation); rewriting_expanditeratively removes that frame cap if multi-thousand-deep chains are needed.
Common mistakes
- Deducting stock inside the verification loop: Running out on the last ingredient leaves earlier ingredients already subtracted, breaking atomicity.
- Releasing the lock between checking and deducting: Two threads can both pass the check on the last units of stock and drive inventory negative.
- Expanding outside the lock in
place_order: A concurrentreplace_recipecan change required ingredients between expansion and deduction. - Assigning instead of adding shared raw counts: Writing
totals[raw_name] = scaled_amountoverwrites earlier paths (bentowould compute8sesameinstead of6 + 8 = 14). - Using a single
visitedset during expansion for cycle checks: Revisiting a finished diamond node (glaze) is valid reuse, not a cycle; only seeing a node currently invisitingindicates a loop. - Forgetting
boolsubclassesint: Withoutnot isinstance(value, bool), Python acceptsTrueas1andFalseas0. - Returning
self._stockdirectly frominventory(): Exposes internal pantry counts to caller mutation outside the lock.
Alternative approaches
- Per-ingredient striped locks: Acquire locks only on the sorted list of raw items needed by an order (sorting lock acquisition order prevents deadlock, where two threads wait forever on each other), allowing non-overlapping orders to run concurrently when paired with an immutable recipe snapshot.
- Relational database transactions: Persist pantry rows in SQL and execute
UPDATE stock SET count = count - :need WHERE name = :item AND count >= :needfor every required item inside a single transaction, rolling back if any row count is0. - Optimistic concurrency control (OCC): Version-stamp stock state, compute order deductions lock-free, and commit via compare-and-swap on the version counter (retrying on contention).
- Materialized raw-requirement cache: Precompute flattened raw totals on each
Recipeand recompute affected ancestors onadd_recipe/replace_recipeto make order-time expansionO(K).
Follow-up questions
- How would you extend the API to fulfill multi-serving batch orders cleanly? Add
servings: int = 1toplace_order, validate_is_int(servings) and servings >= 1, and scale each per-serving entry inneededbyservings(enforcing<= self._max_quantity) before running the locked check-and-deduct loops. That preserves all-or-nothing semantics for the entire batch. If callers instead want partial batch fulfillment ("prepare as many as stock allows"), computefillable = min(self._stock.get(r, 0) // need for r, need in needed.items())under the lock — for instance, if onebrothneeds2kelpand3misoand the pantry holds15kelpand18miso,min(15 // 2, 18 // 3) = min(7, 6) = 6servings can be prepared. - How would the data model evolve if recipe definitions and pantry ledgers required historical versioning? Instead of overwriting entries in
replace_recipe, append immutableRecipeVersion(name, version, ...)records and advance alatest_versionpointer. Specify in the contract whetherDish("glaze")pins an exact version(glaze, v2)or resolves dynamically tolatest_versionat order time, and run cycle checks against that version graph. Pair recipe versions with an append-only ledger of signed stock deltas (+supply,-order_id) so every historical order and pantry balance is auditable. - How could you hold ingredients temporarily for long-running kitchen orders that finish asynchronously? Introduce a two-phase reservation lifecycle:
reserve_order(name, ttl_seconds) -> Optional[reservation_id],commit_reservation(reservation_id), andrelease_reservation(reservation_id). Underself._lock,reserve_ordervalidates stock and moves the required units fromavailableinto areservations[reservation_id]record with an expiry timestamp.commit_reservationfinalizes the deduction andrelease_reservation(or a lazy/background expiry sweep) restores unconfirmed units toavailable, keeping both finalizers idempotent (safe to invoke repeatedly for the samereservation_idwithout double-counting). - How can an order report the exact missing unit counts per ingredient while remaining strictly atomic? During the locked verification loop, inspect every item in
neededrather than returning early on the first shortfall, recordingshortages[raw_name] = amount - availablewheneveravailable < amount. Ifshortagesis non-empty, leave_stockuntouched and return an immutableOrderOutcome(succeeded=False, shortages={"ginger": 1, "sesame": 2}), while keepingplace_order(name) -> boolas a thin wrapper returningplace_order_detailed(name).succeeded. Document thatshortagesreflects the snapshot at that locked check rather than a guarantee for a later call.
Follow-up questions
- How would you extend the API to fulfill multi-serving batch orders cleanly?
- How would the data model evolve if recipe definitions and pantry ledgers required historical versioning?
- How could you hold ingredients temporarily for long-running kitchen orders that finish asynchronously?
- How can an order report the exact missing unit counts per ingredient while remaining strictly atomic?
Similar questions
- Hash Map Lookup and Key-Extraction Complexity Analysis
- Two-Flip Fair Coin Conditional Probabilities
- Optimal Desert Banana Transport with Relay Depots
- Sliding-Window Expiring Key-Value Map
- Mean vs. Median of the Geometric Distribution
- Auditing Methodological Flaws in an ML Pipeline Report
More StackAdapt interview questions
- Sliding-Window Expiring Key-Value Map Easy
- Level-Order Tree Reconstruction from Preorder and Inorder Medium
- Hash Map Lookup and Key-Extraction Complexity Analysis Medium Pro
- Two-Flip Fair Coin Conditional Probabilities Easy Pro
- Optimal Desert Banana Transport with Relay Depots Medium Pro
- Mean vs. Median of the Geometric Distribution Easy Pro
- Auditing Methodological Flaws in an ML Pipeline Report Medium Pro
- Running Median of an Integer Stream Easy Pro
- Single-Pass Uniform k-Item Reservoir Sampling Medium Pro