Versioned Recipe Cart with Bulk Ingredient Pricing

Hard · Software Engineering Fundamentals · Software Engineer · Technical Screen

Problem Statement

Implement an in-memory cart engine for a meal-planning store where shoppers add and remove complete recipes rather than loose items. Every recipe lists the ingredients it needs and their per-recipe unit counts. Because several recipes in a cart may require the same ingredient, pricing is computed on the summed quantity of each ingredient across all currently active recipes:

  • Each entry in ingredient_catalog maps an ingredient_name string to {"base_price": float, "bulk_threshold": int, "bulk_price": float}.
  • When the summed quantity of an ingredient across active recipes is at least bulk_threshold, all units of that ingredient are billed at bulk_price; when the summed quantity is strictly below bulk_threshold, all units are billed at base_price.

An empty cart starts at version 0 with cost 0.0. Every successful cart mutation assigns the next consecutive integer version (1, 2, ...), whereas failed mutations return -1 without advancing the version counter. Cloning the full cart state on every edit would waste memory, so history storage must scale with per-edit changes rather than full snapshots.

Design VersionedRecipeCart and connect it to the judge entry point versioned_recipe_cart(ingredient_catalog, operations, arguments):

  • VersionedRecipeCart(ingredient_catalog): Sets up an empty cart at version 0.
  • add_recipe(recipe_id: str, ingredients: dict[str, int]) -> int: Inserts recipe_id with its ingredient map. If recipe_id is already active in the cart, leaves state unchanged and returns -1. If an ingredient name is missing from ingredient_catalog or has a negative count, raises ValueError without mutating state. Otherwise creates and returns the new version_id.
  • remove_recipe(recipe_id: str) -> int: Deletes recipe_id from the active cart. If recipe_id is not currently active, leaves state unchanged and returns -1. Otherwise creates and returns the new version_id.
  • get_total_cost(version_id: int | None = None) -> float: Returns the cart total at version_id, or at the newest active version when version_id is None (or omitted in arguments as []). Raises ValueError if version_id is not a valid active integer version (0 .. latest_version, rejecting booleans).
  • checkout(version_id: int) -> float: Restores the live cart to version_id, permanently erases every version strictly above version_id (so future edits resume numbering at version_id + 1), and returns the cost at version_id. Raises ValueError if version_id does not exist (rejecting booleans).

In versioned_recipe_cart(ingredient_catalog, operations, arguments), initialize one VersionedRecipeCart(ingredient_catalog), execute each operation in operations with its corresponding argument list in arguments, and return the list of results. Whenever a call raises ValueError, catch it and append "ValueError" to the output list.

Examples

Example 1

Input:
  ingredient_catalog = {
      "flour": {"base_price": 2.0, "bulk_threshold": 4, "bulk_price": 1.5},
      "butter": {"base_price": 5.0, "bulk_threshold": 3, "bulk_price": 4.0},
  }
  operations = ["add_recipe", "get_total_cost", "add_recipe", "get_total_cost", "checkout", "get_total_cost"]
  arguments  = [["focaccia", {"flour": 2, "butter": 1}], [1], ["tart", {"flour": 3, "butter": 2}], [], [1], [2]]

Output:
  [1, 9.0, 2, 19.5, 9.0, "ValueError"]

Walk-through: - Version 0 starts empty at 0.0. - Adding "focaccia" creates version 1: 2 flour (2 * 2.0 = 4.0) plus 1 butter (1 * 5.0 = 5.0) costs 9.0. - Adding "tart" creates version 2: summed quantities reach 5 flour (>= 4, so 5 * 1.5 = 7.5) and 3 butter (>= 3, so 3 * 4.0 = 12.0), totaling 19.5. - checkout(1) rolls the cart back to version 1 (9.0) and deletes version 2, so get_total_cost(2) afterward raises ValueError.

Example 2

Input:
  ingredient_catalog = {
      "tomato": {"base_price": 1.5, "bulk_threshold": 6, "bulk_price": 1.0},
      "olive_oil": {"base_price": 6.0, "bulk_threshold": 2, "bulk_price": 4.5},
  }
  operations = ["add_recipe", "add_recipe", "add_recipe", "get_total_cost", "remove_recipe", "get_total_cost", "get_total_cost"]
  arguments  = [["pasta", {"tomato": 4, "olive_oil": 1}], ["pasta", {"tomato": 2}], ["bruschetta", {"tomato": 3, "olive_oil": 1}], [], ["pasta"], [], [2]]

Output:
  [1, -1, 2, 16.0, 3, 10.5, 16.0]

Walk-through: - "pasta" creates version 1 (4 * 1.5 + 1 * 6.0 = 12.0). - Re-adding "pasta" while it is already active fails with -1 and creates no new version. - "bruschetta" creates version 2: 7 tomatoes (7 * 1.0 = 7.0) and 2 olive oil (2 * 4.5 = 9.0) total 16.0. - Removing "pasta" creates version 3, dropping quantities back below bulk thresholds (3 * 1.5 + 1 * 6.0 = 10.5), while version 2 still reports 16.0.

Constraints

  • 1 <= len(ingredient_catalog) <= 10^4 and 1 <= len(operations) == len(arguments) <= 10^5.
  • For each catalog rule, base_price >= bulk_price >= 0.0 and bulk_threshold >= 1.
  • Valid recipe ingredient counts are non-negative integers; unknown ingredient names or negative counts must raise ValueError without partial cart updates.
  • Valid version_id values are plain integers 0 <= version_id <= latest_version (bool values are invalid and must raise ValueError).
  • Full-cart deep copies per version are not allowed; memory overhead per mutation must be proportional to the number of ingredients in the added or removed recipe.

Step-by-step walkthrough

  1. Understand bulk pricing and version rules

    Our shopping cart holds whole recipes (such as "focaccia" or "tart"), and ingredient quantities are summed across all active recipes before pricing:

    • If an ingredient's summed quantity total_qty >= bulk_threshold, every unit of that ingredient is charged bulk_price.
    • Otherwise, every unit is charged base_price.

    Every successful add_recipe or remove_recipe creates the next sequential version (0 is the initial empty cart, then 1, 2, ...), while failed mutations (-1) create no version, and invalid ingredient inputs raise ValueError without changing state. get_total_cost(v) reads the cost at version v (or the latest version when v is None), and checkout(v) rolls the cart back to v, permanently discards versions > v, and returns version v's cost.

  2. Why copying the cart on every version fails

    If a cart holds 200 recipes and the shopper makes 10,000 edits, copying the entire recipe dictionary on every edit stores 2,000,000 recipe entries—wasting memory and violating the no-deep-copy constraint:

    Naive full snapshots (FORBIDDEN):
      v0: {}
      v1: {r1}
      v2: {r1, r2}
      v3: {r1, r2, r3}   <-- duplicates r1 and r2 all over again!
    
    Delta log + live head (SPACE-EFFICIENT):
      Live head (v3): active_recipes={r1, r2, r3}, ingredient_totals={...}, current_cost=...
      History log:    [None, (+r1, cost_1), (+r2, cost_2), (+r3, cost_3)]
    
  3. Key idea: an undo delta log plus cached version costs

    Look closely at what our two historical operations actually ask for:

    1. get_total_cost(version_id) only asks for a single float. Because ingredient_catalog never changes after initialization, a version's total cost is frozen the instant that version is created! Saving version_costs[v] as one float per version makes every historical cost query an O(1) list lookup—no delta replay or periodic checkpoints needed (checkpoints only become necessary if a future API asks for the full recipe list of an old version without checking it out, which we cover in the follow-ups).
    2. checkout(version_id) moves backward and deletes newer versions. So we keep active_recipes and ingredient_totals for only the newest version, plus one reversible delta (change record) per version: ("add" | "remove", recipe_id, recipe_ingredients). To check out v, we pop deltas from the end of the log down to v + 1 and reverse each one:
      • Undoing "add" deletes recipe_id and subtracts its ingredients.
      • Undoing "remove" puts recipe_id (and its saved recipe_ingredients dictionary) right back and adds its ingredients.

    Because every popped version is permanently discarded, each version can be undone at most once across the entire run!

  4. Maintain aggregated quantities and bulk pricing incrementally

    When one recipe is added or removed, only the ingredients in that recipe change quantity—every other ingredient in the cart keeps its exact same line cost. So instead of rescanning the whole cart, _apply_ingredient_delta subtracts each affected ingredient's old line cost from self.current_cost and adds its new line cost in O(k) time (where k is the number of ingredients in that recipe):

    class VersionedRecipeCart:
        def __init__(self, ingredient_catalog: Dict[str, Dict]) -> None:
            # catalog[name] -> {"base_price": float, "bulk_threshold": int, "bulk_price": float}
            self.catalog = ingredient_catalog
    
            # Live state for ONLY the active latest version (never duplicated across versions):
            # active_recipes[recipe_id] -> {ingredient_name: quantity}, e.g. {"focaccia": {"flour": 2}}
            self.active_recipes: Dict[str, Dict[str, int]] = {}
            # ingredient_totals[name] -> summed quantity across active recipes, e.g. {"flour": 5}
            self.ingredient_totals: Dict[str, int] = {}
            self.current_cost: float = 0.0
    
            # Compact linear history indexed by version_id (0 .. latest_version):
            # version_deltas[v] -> ("add" | "remove", recipe_id, recipe_ingredients) creating version v
            self.version_deltas: List[Optional[Tuple[str, str, Dict[str, int]]]] = [None]
            # version_costs[v] -> total cart cost at version v (0.0 at version 0)
            self.version_costs: List[float] = [0.0]
    
        def latest_version(self) -> int:
            return len(self.version_costs) - 1
    
        def _ingredient_line_cost(self, name: str, total_qty: int) -> float:
            """Compute total cost for `total_qty` units of `name` using all-units bulk pricing."""
            rule = self.catalog[name]
            # Uses >= because hitting bulk_threshold reprices EVERY unit to bulk_price.
            if total_qty >= rule["bulk_threshold"]:
                return total_qty * rule["bulk_price"]
            return total_qty * rule["base_price"]
    
        def _apply_ingredient_delta(self, recipe_ingredients: Dict[str, int], sign: int) -> None:
            """Add (sign=+1) or subtract (sign=-1) a recipe's ingredients and update current_cost."""
            for name, qty in recipe_ingredients.items():
                old_qty = self.ingredient_totals.get(name, 0)
                new_qty = old_qty + sign * qty
    
                # Only ingredients in this recipe can change tier, so swap old vs new line cost.
                old_line_cost = self._ingredient_line_cost(name, old_qty)
                new_line_cost = self._ingredient_line_cost(name, new_qty)
                self.current_cost += new_line_cost - old_line_cost
    
                if new_qty == 0:
                    self.ingredient_totals.pop(name, None)
                else:
                    self.ingredient_totals[name] = new_qty
    
            # Keep an empty cart at exact 0.0 so float rounding residue never lingers.
            if not self.ingredient_totals:
                self.current_cost = 0.0
    
  5. Add and remove recipes atomically

    Two small details make add_recipe and remove_recipe completely bug-free:

    1. Validate before mutating: add_recipe checks every ingredient before updating active_recipes or ingredient_totals, so an error can never leave the cart half-applied. It also copies dict(ingredients) once when added so external edits by the caller cannot corrupt history.
    2. Keep the dictionary reference on remove_recipe: when removing a recipe, we store a pointer to the popped recipe_ingredients dictionary inside version_deltas (zero extra copies!). That way, if checkout later undoes the removal, we still know the exact ingredients that recipe had at that point in history—even if the same recipe_id was later re-added with different ingredients.
        def _record_version(
            self,
            action: str,
            recipe_id: str,
            recipe_ingredients: Dict[str, int],
        ) -> int:
            self.version_deltas.append((action, recipe_id, recipe_ingredients))
            self.version_costs.append(self.current_cost)
            return self.latest_version()
    
        def add_recipe(self, recipe_id: str, ingredients: Dict[str, int]) -> int:
            # Duplicate recipe in the active cart fails without creating a new version.
            if recipe_id in self.active_recipes:
                return -1
    
            # Phase 1: Validate all ingredients BEFORE mutating state so errors leave no partial edit.
            for name, qty in ingredients.items():
                if name not in self.catalog:
                    raise ValueError(f"unknown ingredient: {name!r}")
                if qty < 0:
                    raise ValueError(f"negative quantity for {name!r}")
    
            # Phase 2: Copy the caller's dict once so external edits later cannot alter our history.
            recipe_ingredients = dict(ingredients)
            self.active_recipes[recipe_id] = recipe_ingredients
            self._apply_ingredient_delta(recipe_ingredients, +1)
            return self._record_version("add", recipe_id, recipe_ingredients)
    
        def remove_recipe(self, recipe_id: str) -> int:
            # Missing recipe in the active cart fails without creating a new version.
            if recipe_id not in self.active_recipes:
                return -1
    
            recipe_ingredients = self.active_recipes.pop(recipe_id)
            self._apply_ingredient_delta(recipe_ingredients, -1)
            # Reuse the same dict reference in the log so checkout can restore it without copying.
            return self._record_version("remove", recipe_id, recipe_ingredients)
    
  6. Query historical costs and roll back on checkout

    In _validate_version_id, notice we check isinstance(version_id, bool) before isinstance(version_id, int) because in Python bool is a subclass of int (True == 1 and False == 0).

    During checkout(version_id), we validate version_id first, then pop and reverse deltas until self.latest_version() == version_id. Because version_deltas and version_costs now have length version_id + 1, all versions > version_id are gone and the very next successful edit will automatically become version_id + 1. Resetting self.current_cost = self.version_costs[version_id] at the end prevents tiny floating-point rounding differences from building up across rollbacks.

        def _validate_version_id(self, version_id: Any) -> None:
            # Check bool explicitly because bool is a subclass of int in Python (True == 1).
            if isinstance(version_id, bool) or not isinstance(version_id, int):
                raise ValueError(f"invalid version_id: {version_id!r}")
            if version_id < 0 or version_id > self.latest_version():
                raise ValueError(f"invalid version_id: {version_id!r}")
    
        def get_total_cost(self, version_id: Optional[int] = None) -> float:
            if version_id is None:
                return self.version_costs[-1]
            self._validate_version_id(version_id)
            return self.version_costs[version_id]
    
        def checkout(self, version_id: int) -> float:
            self._validate_version_id(version_id)
    
            # Pop and reverse each newer version until `version_id` becomes the active head.
            while self.latest_version() > version_id:
                delta = self.version_deltas.pop()
                self.version_costs.pop()
                assert delta is not None
                action, recipe_id, recipe_ingredients = delta
    
                if action == "add":
                    # Undo an addition by removing the recipe and subtracting its quantities.
                    del self.active_recipes[recipe_id]
                    self._apply_ingredient_delta(recipe_ingredients, -1)
                else:
                    # Undo a removal by putting the exact recipe dict back and adding its quantities.
                    self.active_recipes[recipe_id] = recipe_ingredients
                    self._apply_ingredient_delta(recipe_ingredients, +1)
    
            # Snap to the stored cost at `version_id` so float rounding cannot accumulate across rollbacks.
            self.current_cost = self.version_costs[version_id]
            return self.current_cost
    
  7. Trace Example 1 step by step

    Catalog: flour (2.0 base, 1.5 at >= 4), butter (5.0 base, 4.0 at >= 3).

    Call                                         Live totals            version_costs        Return
    ------------------------------------------------------------------------------------------------
    init                                         {}                     [0.0]                -
    add_recipe("focaccia", {flour:2, butter:1})  {flour:2, butter:1}    [0.0, 9.0]           1
    get_total_cost(1)                            (unchanged)            [0.0, 9.0]           9.0
    add_recipe("tart", {flour:3, butter:2})      {flour:5, butter:3}    [0.0, 9.0, 19.5]     2
    get_total_cost()                             (unchanged)            [0.0, 9.0, 19.5]     19.5
    checkout(1) -> pops & undoes "add tart"      {flour:2, butter:1}    [0.0, 9.0]           9.0
    get_total_cost(2)                            2 > latest_version(1)  [0.0, 9.0]           ValueError
    

    Notice on add_recipe("tart", ...): flour jumps from 2 (2 * 2.0 = 4.0) to 5 >= 4, repricing all 5 units to 5 * 1.5 = 7.5, while butter jumps from 1 (5.0) to 3 >= 3 (3 * 4.0 = 12.0), giving 7.5 + 12.0 = 19.5.

  8. Complete solution

    The judge driver versioned_recipe_cart dispatches each operation to our VersionedRecipeCart instance and converts any raised ValueError into the string "ValueError".

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class VersionedRecipeCart:
        def __init__(self, ingredient_catalog: Dict[str, Dict]) -> None:
            # catalog[name] -> {"base_price": float, "bulk_threshold": int, "bulk_price": float}
            self.catalog = ingredient_catalog
    
            # Live state for ONLY the active latest version (never duplicated across versions):
            # active_recipes[recipe_id] -> {ingredient_name: quantity}, e.g. {"focaccia": {"flour": 2}}
            self.active_recipes: Dict[str, Dict[str, int]] = {}
            # ingredient_totals[name] -> summed quantity across active recipes, e.g. {"flour": 5}
            self.ingredient_totals: Dict[str, int] = {}
            self.current_cost: float = 0.0
    
            # Compact linear history indexed by version_id (0 .. latest_version):
            # version_deltas[v] -> ("add" | "remove", recipe_id, recipe_ingredients) creating version v
            self.version_deltas: List[Optional[Tuple[str, str, Dict[str, int]]]] = [None]
            # version_costs[v] -> total cart cost at version v (0.0 at version 0)
            self.version_costs: List[float] = [0.0]
    
        def latest_version(self) -> int:
            return len(self.version_costs) - 1
    
        def _ingredient_line_cost(self, name: str, total_qty: int) -> float:
            """Compute total cost for `total_qty` units of `name` using all-units bulk pricing."""
            rule = self.catalog[name]
            # Uses >= because hitting bulk_threshold reprices EVERY unit to bulk_price.
            if total_qty >= rule["bulk_threshold"]:
                return total_qty * rule["bulk_price"]
            return total_qty * rule["base_price"]
    
        def _apply_ingredient_delta(self, recipe_ingredients: Dict[str, int], sign: int) -> None:
            """Add (sign=+1) or subtract (sign=-1) a recipe's ingredients and update current_cost."""
            for name, qty in recipe_ingredients.items():
                old_qty = self.ingredient_totals.get(name, 0)
                new_qty = old_qty + sign * qty
    
                # Only ingredients in this recipe can change tier, so swap old vs new line cost.
                old_line_cost = self._ingredient_line_cost(name, old_qty)
                new_line_cost = self._ingredient_line_cost(name, new_qty)
                self.current_cost += new_line_cost - old_line_cost
    
                if new_qty == 0:
                    self.ingredient_totals.pop(name, None)
                else:
                    self.ingredient_totals[name] = new_qty
    
            # Keep an empty cart at exact 0.0 so float rounding residue never lingers.
            if not self.ingredient_totals:
                self.current_cost = 0.0
    
        def _record_version(
            self,
            action: str,
            recipe_id: str,
            recipe_ingredients: Dict[str, int],
        ) -> int:
            self.version_deltas.append((action, recipe_id, recipe_ingredients))
            self.version_costs.append(self.current_cost)
            return self.latest_version()
    
        def _validate_version_id(self, version_id: Any) -> None:
            # Check bool explicitly because bool is a subclass of int in Python (True == 1).
            if isinstance(version_id, bool) or not isinstance(version_id, int):
                raise ValueError(f"invalid version_id: {version_id!r}")
            if version_id < 0 or version_id > self.latest_version():
                raise ValueError(f"invalid version_id: {version_id!r}")
    
        def add_recipe(self, recipe_id: str, ingredients: Dict[str, int]) -> int:
            # Duplicate recipe in the active cart fails without creating a new version.
            if recipe_id in self.active_recipes:
                return -1
    
            # Phase 1: Validate all ingredients BEFORE mutating state so errors leave no partial edit.
            for name, qty in ingredients.items():
                if name not in self.catalog:
                    raise ValueError(f"unknown ingredient: {name!r}")
                if qty < 0:
                    raise ValueError(f"negative quantity for {name!r}")
    
            # Phase 2: Copy the caller's dict once so external edits later cannot alter our history.
            recipe_ingredients = dict(ingredients)
            self.active_recipes[recipe_id] = recipe_ingredients
            self._apply_ingredient_delta(recipe_ingredients, +1)
            return self._record_version("add", recipe_id, recipe_ingredients)
    
        def remove_recipe(self, recipe_id: str) -> int:
            # Missing recipe in the active cart fails without creating a new version.
            if recipe_id not in self.active_recipes:
                return -1
    
            recipe_ingredients = self.active_recipes.pop(recipe_id)
            self._apply_ingredient_delta(recipe_ingredients, -1)
            # Reuse the same dict reference in the log so checkout can restore it without copying.
            return self._record_version("remove", recipe_id, recipe_ingredients)
    
        def get_total_cost(self, version_id: Optional[int] = None) -> float:
            if version_id is None:
                return self.version_costs[-1]
            self._validate_version_id(version_id)
            return self.version_costs[version_id]
    
        def checkout(self, version_id: int) -> float:
            self._validate_version_id(version_id)
    
            # Pop and reverse each newer version until `version_id` becomes the active head.
            while self.latest_version() > version_id:
                delta = self.version_deltas.pop()
                self.version_costs.pop()
                assert delta is not None
                action, recipe_id, recipe_ingredients = delta
    
                if action == "add":
                    # Undo an addition by removing the recipe and subtracting its quantities.
                    del self.active_recipes[recipe_id]
                    self._apply_ingredient_delta(recipe_ingredients, -1)
                else:
                    # Undo a removal by putting the exact recipe dict back and adding its quantities.
                    self.active_recipes[recipe_id] = recipe_ingredients
                    self._apply_ingredient_delta(recipe_ingredients, +1)
    
            # Snap to the stored cost at `version_id` so float rounding cannot accumulate across rollbacks.
            self.current_cost = self.version_costs[version_id]
            return self.current_cost
    
    
    def versioned_recipe_cart(
        ingredient_catalog: Dict[str, Dict],
        operations: List[str],
        arguments: List[List],
    ) -> List:
        cart = VersionedRecipeCart(ingredient_catalog)
        results: List[Any] = []
    
        for op_name, op_args in zip(operations, arguments):
            try:
                if op_name == "add_recipe":
                    results.append(cart.add_recipe(op_args[0], op_args[1]))
                elif op_name == "remove_recipe":
                    results.append(cart.remove_recipe(op_args[0]))
                elif op_name == "get_total_cost":
                    if len(op_args) == 0:
                        results.append(cart.get_total_cost())
                    else:
                        results.append(cart.get_total_cost(op_args[0]))
                elif op_name == "checkout":
                    results.append(cart.checkout(op_args[0]))
                else:
                    raise ValueError(f"unknown operation: {op_name!r}")
            except ValueError:
                results.append("ValueError")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of editing a shopping list with an "Undo" stack while writing the updated dollar total on a numbered log sheet after every edit. Instead of photocopying the entire cart on each edit, we maintain only one live cart for the newest version, append a tiny reversible delta—a record storing just what changed in that single step (("add" | "remove", recipe_id, ingredients))—and append that version's computed float total to version_costs. Reading any historical version's cost is an instant version_costs[v] lookup, and calling checkout(v) simply pops and undoes deltas from the end of the stack until version v is once again on top.

The naive approach deep-copies the full recipe map and ingredient totals on every edit, then sums and prices every recipe from scratch on each get_total_cost call. With hundreds of recipes in a cart and thousands of edits, copying the whole cart uses O(versions * cart_size) memory—exhausting RAM and violating the problem's explicit constraint—while rescanning unchanged ingredients repeats work on every mutation and read.

Walk through a 4-step sequence with flour (2.0 base, 1.5 bulk at >= 4):

  • Start (v0): Empty cart, version_costs = [0.0].
  • add_recipe("focaccia", {"flour": 2}) -> v1: flour becomes 2 (< 4), line cost 2 * 2.0 = 4.0; log saves ("add", "focaccia", {"flour": 2}), version_costs = [0.0, 4.0].
  • add_recipe("tart", {"flour": 3}) -> v2: flour jumps from 2 to 5 (>= 4), repricing all 5 units to 5 * 1.5 = 7.5; current_cost updates by +7.5 - 4.0 = +3.5 -> 7.5, version_costs = [0.0, 4.0, 7.5].
  • checkout(1): Pops v2, deletes "tart", subtracts 3 flour back to 2, truncates version_costs to [0.0, 4.0], and returns 4.0 (v2 now raises ValueError).

Complexity

Let k be the number of distinct ingredients in the recipe being added or removed, V the number of currently retained versions, and S the sum of k across all "add" operations in the retained history.

  • add_recipe and remove_recipe: O(k) time. Only the k ingredients inside that single recipe change quantity, so we update k dictionary entries and swap k old-vs-new line costs in O(1) time each.
  • get_total_cost: O(1) time. Because catalog prices never change, every version's total is stored in version_costs[v] at creation time and read by direct index lookup.
  • checkout: O(sum of k over discarded versions) worst-case time, O(1) amortized overhead per mutation. Here amortized time means the average cost per operation over a whole sequence: even if one checkout undoes 100 versions at once, each version is permanently deleted when popped and can never be undone a second time, so total undo work across the entire run never exceeds the O(k) work already spent creating those versions.
  • Space: O(V + S). Each version adds one 3-tuple and one float (O(1) per version), each added recipe copies its k-item ingredients dict once (remove shares a reference to that exact dict without copying), and active_recipes plus ingredient_totals hold only the single active head.

Edge cases

  • Failed add_recipe or remove_recipe: Adding an already-active recipe_id or removing a missing one returns -1 and does not increment latest_version().
  • Exact bulk threshold (total_qty == bulk_threshold): Uses >=, so hitting the threshold immediately reprices all units of that ingredient at bulk_price.
  • Dropping back below bulk_threshold on remove_recipe or checkout: Subtracting a recipe's ingredients swaps the line cost back to base_price for all remaining units.
  • checkout(0) and checkout(latest_version): checkout(0) empties the cart and resets version numbering so the next edit becomes 1; checkout(latest_version) pops nothing and returns current_cost.
  • Re-adding a removed recipe_id with different ingredients: Because each "remove" delta keeps a direct reference to the exact ingredients dict that was popped at that moment, rolling back past a later re-add restores the exact ingredients from the earlier version.
  • Invalid version_id (< 0, > latest_version, discarded versions, or bool): Raises ValueError before modifying any state; checking isinstance(version_id, bool) explicitly rejects True and False (which subclass int in Python).
  • Floating-point rounding drift: Snapping self.current_cost = self.version_costs[version_id] after checkout and resetting 0.0 when ingredient_totals becomes empty prevents tiny binary-float rounding errors from accumulating.

Common mistakes

  • Applying bulk discounts per recipe instead of across the whole cart: Two recipes with 2 and 3 flour must combine to 5 >= 4 and trigger bulk pricing together.
  • Charging bulk_price only on units above bulk_threshold: The specification charges every unit at bulk_price once total_qty >= bulk_threshold, not tiered marginal brackets.
  • Deep-copying active_recipes or ingredient_totals per version: Violates the memory constraint and turns O(k) mutations into O(cart_size) copies.
  • Storing only (action, recipe_id) in "remove" deltas without the removed ingredients dict: Makes it impossible to restore the recipe's quantities during checkout, or restores the wrong quantities if the same recipe_id was later re-added with modified ingredients.
  • Forgetting to truncate discarded versions on checkout(v): After checkout(1), get_total_cost(2) must raise ValueError, and the next successful edit must receive version ID 2, not 3.
  • Mutating state before input validation finishes: Performing atomic mutation—meaning an operation either succeeds completely or changes nothing at all—requires checking all ingredients before updating any running totals.

Follow-up questions

  • How would you extend the data model to allow branching timelines and merging two cart versions instead of deleting newer versions on checkout? Replace the flat array log with a version tree where each node v stores (parent_id, delta, cost) and checkout(target_v) never deletes nodes—instead, find the lowest common ancestor (LCA) (the deepest shared ancestor version of the current head u and target_v), walk upward from u to the LCA undoing deltas, and walk downward from the LCA to target_v reapplying deltas. Named branches are just a branch_name -> version_id dictionary, and merging branch B into A compares A and B against their LCA, combining non-overlapping recipe additions/removals and raising a merge conflict if both branches added the same recipe_id with different ingredient maps.
  • Suppose historical state reads happen 100 times more often than cart edits, and callers also query the full ingredient list of old versions—how would you choose a snapshot interval to balance memory against read latency? For get_total_cost(v) alone, storing version_costs[v] already serves every historical read in O(1) time with just one float per version; when reads also inspect the full recipe/ingredient contents of arbitrary versions without moving the head, store a full checkpoint snapshot every K versions so any version v is reconstructed by loading checkpoint (v // K) * K and replaying at most K - 1 deltas (K / 2 on average). Balancing snapshot memory (V / K) * C (for cart size C) against read replay work R * (K / 2) * k (for R reads) shrinks the optimal interval K inversely with sqrt(R)—so 100x more reads calls for 10x more frequent checkpoints, paired with a small LRU cache (a fixed-size cache that evicts the least-recently-used version first) or a persistent tree map (a tree that shares unchanged branches across versions in O(k log C) space per edit and O(log C) lookup time).
  • If several worker threads call add_recipe, remove_recipe, and checkout on the same cart concurrently, how would you keep validation and state updates atomic? Protect the cart with a readers-writer lock—a lock allowing many get_total_cost readers to run concurrently while giving add_recipe, remove_recipe, and checkout exclusive write access across their entire validate-mutate-record sequence so two threads can never interleave partial ingredient updates or assign duplicate version IDs. To also prevent "lost updates" where Thread A adds a recipe assuming version 5 is active right after Thread B checked out version 2, add optimistic concurrency control—requiring mutations to pass expected_version_id and rejecting the call if latest_version() != expected_version_id so the caller can refresh and retry cleanly.

Follow-up questions

Similar questions

More Decagon interview questions

All 20 Decagon questions →