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 to name in the raw pantry inventory.
  • Dish(name: str) — points to another stored recipe named name.
  • 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 where max_quantity bounds every ingredient count, pantry stock balance, and expanded raw requirement. Raises ValueError if max_quantity is not an integer >= 1 (bool values such as True are 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 TypeError if ingredients is not a dict or any key is neither Raw nor Dish.
    • Raises ValueError if name is not a non-empty str, prep_minutes is not an integer >= 0, ingredients is empty, any referenced Raw/Dish has an empty or non-str name, any quantity is not an integer in 1..max_quantity, name is already stored, or adding the recipe would close a direct or indirect dependency cycle among stored recipes.
    • Forward references (Dish entries naming recipes that have not been added yet) are allowed on write.
    • On any exception, stored state remains untouched. Mutating the caller's ingredients dictionary after add_recipe returns must not alter the stored recipe.
  • 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 as add_recipe, raising KeyError if name is not currently stored.
  • add_supply(name: str, count: int) -> None: Adds count units of raw pantry item name. Raises ValueError if name is not a non-empty str, count is not an integer >= 1, or the updated balance would exceed max_quantity.
  • place_order(name: str) -> bool: Attempts to prepare one serving of recipe name atomically. Nested Dish requirements multiply along dependency chains and sum across multiple paths reaching the same Raw item. Returns True and deducts all required raw quantities together if name exists, every reachable Dish is defined, no cycle exists, no intermediate or final raw requirement exceeds max_quantity, and every required raw item has stock >= required; otherwise returns False and leaves all stock counts unchanged.
  • get_recipe(name: str) -> Optional[Recipe]: Returns the immutable Recipe for name, or None if not found.
  • stock(name: str) -> int: Returns the available pantry count of raw item name (0 if never supplied).
  • inventory() -> Dict[str, int]: Returns a newly allocated dictionary of all supplied raw items (including those depleted to 0) sorted ascending by item name.
  • recipes_with_prep_time_above(threshold: int) -> List[str]: Returns a sorted list of recipe names whose own stored prep_minutes is strictly greater than threshold (>), 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 of name regardless of current pantry stock, or None if name cannot be expanded (unknown recipe, missing nested Dish, cycle, or over max_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_quantity is an integer >= 1 (defaults to 2**63 - 1).
  • Recipe names and raw ingredient names are non-empty strings in separate namespaces (Raw("x") vs Dish("x")).
  • prep_minutes is an integer >= 0; every ingredient quantity and add_supply count is an integer in 1..max_quantity (bool is 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

  1. 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 RecipeService
    Can 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") or Dish("x"), never a bare str.
    How are duplicate recipe names handled? add_recipe raises ValueError; replace_recipe overwrites an existing recipe (and raises KeyError if absent).
    Are forward references permitted? Yes. A recipe may reference a Dish that has not been added yet; expanding or ordering it simply fails until that sub-recipe exists.
    When are dependency cycles caught? Eagerly inside add_recipe and replace_recipe, guaranteeing the stored graph is always loop-free.
    Which numeric values are valid? Quantities, supply increments, and expanded totals must be int values (never bool) in 1..max_quantity. prep_minutes is an int >= 0.
    What makes place_order atomic? Either True is returned and every required raw count is subtracted together, or False is returned and zero counts change.
    How does recipes_with_prep_time_above filter? Strict > against each recipe's own stored prep_minutes (nested sub-recipe times are not summed), returning sorted names.
    Can callers mutate internal records via getters? No. Stored Recipe objects are frozen and dictionary/list getters return fresh copies.

    A single threading.Lock guards all reads and writes so concurrent threads observe consistent state.

  2. 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") and Dish("glaze") hash and compare as distinct keys even though both wrap "glaze", so a recipe can use both simultaneously.
    • Marking Raw, Dish, and Recipe with @dataclass(frozen=True) makes them immutable (reassigning any field raises FrozenInstanceError), and storing ingredients as an immutable tuple of (ref, quantity) pairs lets get_recipe return a Recipe directly without defensive copying.
    • Because bool inherits from int in Python (isinstance(True, int) is True), helper _is_int explicitly rejects booleans so True never sneaks through as 1.
    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)
    
  3. Validate inputs before mutating recipes or stock

    Every write method follows validate first, mutate once. _build_recipe validates types and bounds and snapshots the caller's ingredients dictionary into a tuple before acquiring self._lock — so if the caller edits their dictionary later, the stored Recipe cannot change.

    add_supply enforces count >= 1 and checks new_count <= self._max_quantity before updating _stock, keeping every stock entry inside 0..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))
    
  4. 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 -> dumpling means "bento requires Dish('dumpling')". A loop such as glaze -> bento -> dumpling -> glaze or loop -> loop would make expansion infinite.

    Because every previously stored recipe passed cycle checking, self._recipes is already acyclic. Thus, inserting or replacing name can only close a cycle that starts at name's new Dish references and reaches name again:

    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_cycle handle replacements and forward references effortlessly: - Checking current == name before reading self._recipes[name] ensures we never traverse name's old edges during a replace_recipe call. - Skipping current not in self._recipes treats 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 False
    
  5. Flatten 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 like glaze are 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) verifies new_total <= self._max_quantity on 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_total
    
  6. Execute 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):

    1. Expand name into needed without touching _stock. Unknown recipes, missing forward-referenced dishes, and max_quantity overflows raise _InvalidOrder and return False.
    2. Verify available >= amount for every entry in needed. In Example 1, when ramen has enough kelp, miso, noodles, and soy but 0 ginger, returning False during this check loop leaves the other four ingredients untouched.
    3. Deduct every amount from self._stock and return True.

    Holding self._lock across all three phases stops two concurrent place_order("latte") threads (each needing 2 beans when stock["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 -> False
    

    Keeping _expand inside the lock also prevents a concurrent replace_recipe from 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
    
  7. Return sorted, mutation-safe views from read methods

    All query methods acquire self._lock for a consistent view and return either frozen objects or defensive copies (newly allocated containers that callers can edit without corrupting internal state):

    • get_recipe returns the stored Recipe directly because Recipe, its ingredients tuple, and every Raw/Dish element are frozen.
    • inventory and raw_requirements allocate new dictionaries with keys sorted alphabetically.
    • recipes_with_prep_time_above compares recipe.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 result
    
  8. Full 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_order and raw_requirements — O(E * K) time, O(V * K) space: Because memo caches each reachable sub-recipe's raw dictionary, each of the V recipes expands once, and each of the E edges merges at most K raw entries into its parent dictionary. Verifying and deducting stock takes O(K) hash-map lookups, and raw_requirements adds O(K log K) to sort the K raw names. Space is O(V * K) for up to V cached dictionaries of size at most K, plus O(V) call-stack depth.
  • Why memoization matters in numbers: In a 30-level diamond chain where r_i uses Dish("a_i") and Dish("b_i") and both point to Dish("r_{i+1}"), unmemoized recursion walks 2^30 = 1,073,741,824 paths, whereas memoization visits each of the 91 recipes once.
  • add_recipe and replace_recipe — O(I + V' + E') time, O(I + V') space: Validating and freezing I ingredient pairs costs O(I), and _creates_cycle explores at most V' reachable recipes and E' edges once using a seen set of size O(V').
  • add_supply, stock, and get_recipe — O(1) average time, O(1) extra space: Each performs a constant number of dictionary operations under self._lock.
  • inventory — O(S log S) time, O(S) space: Allocates a fresh dictionary over all S supplied raw items in sorted order.
  • recipes_with_prep_time_above — O(N + M log M) time, O(M) space: Scans all N stored recipes once and sorts the M matching names.

Edge cases

  • Exact pantry balance: Fulfilling an order with zero units to spare leaves the raw key in _stock mapped to 0 rather than removing the entry.
  • Unsupplied raw item: self._stock.get(raw_name, 0) treats never-supplied ingredients as 0, causing orders needing them to return False cleanly.
  • Forward references: bento -> Dish("dumpling") can be stored before dumpling exists; place_order("bento") returns False and raw_requirements("bento") returns None until dumpling is added.
  • Direct, indirect, and replacement cycles: loop -> loop, x -> y -> z -> x, and replacing glaze to depend on bento all raise ValueError and preserve prior state.
  • Updating a shared sub-recipe: replace_recipe immediately affects future place_order and raw_requirements calls without altering already-completed orders.
  • Shared name across namespaces: Raw("glaze") and Dish("glaze") remain distinct keys and can appear together in one recipe.
  • Malformed inputs: 0, negative numbers, True/False booleans, floats, strings as counts, empty names, and empty ingredient dicts raise ValueError or TypeError before touching state.
  • max_quantity cap: Totals equal to max_quantity succeed when stocked, whereas max_quantity + 1 aborts cleanly via _InvalidOrder.
  • Deep linear chains: Python recursion hits RecursionError past ~1,000 nested levels (still before any stock mutation); rewriting _expand iteratively 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 concurrent replace_recipe can change required ingredients between expansion and deduction.
  • Assigning instead of adding shared raw counts: Writing totals[raw_name] = scaled_amount overwrites earlier paths (bento would compute 8 sesame instead of 6 + 8 = 14).
  • Using a single visited set during expansion for cycle checks: Revisiting a finished diamond node (glaze) is valid reuse, not a cycle; only seeing a node currently in visiting indicates a loop.
  • Forgetting bool subclasses int: Without not isinstance(value, bool), Python accepts True as 1 and False as 0.
  • Returning self._stock directly from inventory(): 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 >= :need for every required item inside a single transaction, rolling back if any row count is 0.
  • 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 Recipe and recompute affected ancestors on add_recipe / replace_recipe to make order-time expansion O(K).

Follow-up questions

  • How would you extend the API to fulfill multi-serving batch orders cleanly? Add servings: int = 1 to place_order, validate _is_int(servings) and servings >= 1, and scale each per-serving entry in needed by servings (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"), compute fillable = min(self._stock.get(r, 0) // need for r, need in needed.items()) under the lock — for instance, if one broth needs 2 kelp and 3 miso and the pantry holds 15 kelp and 18 miso, min(15 // 2, 18 // 3) = min(7, 6) = 6 servings 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 immutable RecipeVersion(name, version, ...) records and advance a latest_version pointer. Specify in the contract whether Dish("glaze") pins an exact version (glaze, v2) or resolves dynamically to latest_version at 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), and release_reservation(reservation_id). Under self._lock, reserve_order validates stock and moves the required units from available into a reservations[reservation_id] record with an expiry timestamp. commit_reservation finalizes the deduction and release_reservation (or a lazy/background expiry sweep) restores unconfirmed units to available, keeping both finalizers idempotent (safe to invoke repeatedly for the same reservation_id without 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 needed rather than returning early on the first shortfall, recording shortages[raw_name] = amount - available whenever available < amount. If shortages is non-empty, leave _stock untouched and return an immutable OrderOutcome(succeeded=False, shortages={"ginger": 1, "sesame": 2}), while keeping place_order(name) -> bool as a thin wrapper returning place_order_detailed(name).succeeded. Document that shortages reflects the snapshot at that locked check rather than a guarantee for a later call.

Follow-up questions

Similar questions

More StackAdapt interview questions

All 10 StackAdapt questions →