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_catalogmaps aningredient_namestring 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 atbulk_price; when the summed quantity is strictly belowbulk_threshold, all units are billed atbase_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 version0.add_recipe(recipe_id: str, ingredients: dict[str, int]) -> int: Insertsrecipe_idwith its ingredient map. Ifrecipe_idis already active in the cart, leaves state unchanged and returns-1. If an ingredient name is missing fromingredient_catalogor has a negative count, raisesValueErrorwithout mutating state. Otherwise creates and returns the newversion_id.remove_recipe(recipe_id: str) -> int: Deletesrecipe_idfrom the active cart. Ifrecipe_idis not currently active, leaves state unchanged and returns-1. Otherwise creates and returns the newversion_id.get_total_cost(version_id: int | None = None) -> float: Returns the cart total atversion_id, or at the newest active version whenversion_idisNone(or omitted inargumentsas[]). RaisesValueErrorifversion_idis not a valid active integer version (0 .. latest_version, rejecting booleans).checkout(version_id: int) -> float: Restores the live cart toversion_id, permanently erases every version strictly aboveversion_id(so future edits resume numbering atversion_id + 1), and returns the cost atversion_id. RaisesValueErrorifversion_iddoes 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^4and1 <= len(operations) == len(arguments) <= 10^5.- For each catalog rule,
base_price >= bulk_price >= 0.0andbulk_threshold >= 1. - Valid recipe ingredient counts are non-negative integers; unknown ingredient names or negative counts must raise
ValueErrorwithout partial cart updates. - Valid
version_idvalues are plain integers0 <= version_id <= latest_version(boolvalues are invalid and must raiseValueError). - 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
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 chargedbulk_price. - Otherwise, every unit is charged
base_price.
Every successful
add_recipeorremove_recipecreates the next sequential version (0is the initial empty cart, then1,2, ...), while failed mutations (-1) create no version, and invalid ingredient inputs raiseValueErrorwithout changing state.get_total_cost(v)reads the cost at versionv(or the latest version whenvisNone), andcheckout(v)rolls the cart back tov, permanently discards versions> v, and returns versionv's cost.- If an ingredient's summed quantity
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,000recipe 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)]Key idea: an undo delta log plus cached version costs
Look closely at what our two historical operations actually ask for:
get_total_cost(version_id)only asks for a single float. Becauseingredient_catalognever changes after initialization, a version's total cost is frozen the instant that version is created! Savingversion_costs[v]as one float per version makes every historical cost query anO(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).checkout(version_id)moves backward and deletes newer versions. So we keepactive_recipesandingredient_totalsfor only the newest version, plus one reversible delta (change record) per version:("add" | "remove", recipe_id, recipe_ingredients). To check outv, we pop deltas from the end of the log down tov + 1and reverse each one:- Undoing
"add"deletesrecipe_idand subtracts its ingredients. - Undoing
"remove"putsrecipe_id(and its savedrecipe_ingredientsdictionary) right back and adds its ingredients.
- Undoing
Because every popped version is permanently discarded, each version can be undone at most once across the entire run!
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_deltasubtracts each affected ingredient's old line cost fromself.current_costand adds its new line cost inO(k)time (wherekis 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.0Add and remove recipes atomically
Two small details make
add_recipeandremove_recipecompletely bug-free:- Validate before mutating:
add_recipechecks every ingredient before updatingactive_recipesoringredient_totals, so an error can never leave the cart half-applied. It also copiesdict(ingredients)once when added so external edits by the caller cannot corrupt history. - Keep the dictionary reference on
remove_recipe: when removing a recipe, we store a pointer to the poppedrecipe_ingredientsdictionary insideversion_deltas(zero extra copies!). That way, ifcheckoutlater undoes the removal, we still know the exact ingredients that recipe had at that point in history—even if the samerecipe_idwas 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)- Validate before mutating:
Query historical costs and roll back on checkout
In
_validate_version_id, notice we checkisinstance(version_id, bool)beforeisinstance(version_id, int)because in Pythonboolis a subclass ofint(True == 1andFalse == 0).During
checkout(version_id), we validateversion_idfirst, then pop and reverse deltas untilself.latest_version() == version_id. Becauseversion_deltasandversion_costsnow have lengthversion_id + 1, all versions> version_idare gone and the very next successful edit will automatically becomeversion_id + 1. Resettingself.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_costTrace Example 1 step by step
Catalog:
flour(2.0base,1.5at>= 4),butter(5.0base,4.0at>= 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] ValueErrorNotice on
add_recipe("tart", ...):flourjumps from2(2 * 2.0 = 4.0) to5 >= 4, repricing all 5 units to5 * 1.5 = 7.5, whilebutterjumps from1(5.0) to3 >= 3(3 * 4.0 = 12.0), giving7.5 + 12.0 = 19.5.Complete solution
The judge driver
versioned_recipe_cartdispatches each operation to ourVersionedRecipeCartinstance and converts any raisedValueErrorinto 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:flourbecomes2(< 4), line cost2 * 2.0 = 4.0; log saves("add", "focaccia", {"flour": 2}),version_costs = [0.0, 4.0].add_recipe("tart", {"flour": 3})->v2:flourjumps from2to5(>= 4), repricing all 5 units to5 * 1.5 = 7.5;current_costupdates by+7.5 - 4.0 = +3.5->7.5,version_costs = [0.0, 4.0, 7.5].checkout(1): Popsv2, deletes"tart", subtracts3flour back to2, truncatesversion_coststo[0.0, 4.0], and returns4.0(v2now raisesValueError).
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_recipeandremove_recipe:O(k)time. Only thekingredients inside that single recipe change quantity, so we updatekdictionary entries and swapkold-vs-new line costs inO(1)time each.get_total_cost:O(1)time. Because catalog prices never change, every version's total is stored inversion_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 onecheckoutundoes 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 theO(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 itsk-itemingredientsdict once (removeshares a reference to that exact dict without copying), andactive_recipesplusingredient_totalshold only the single active head.
Edge cases
- Failed
add_recipeorremove_recipe: Adding an already-activerecipe_idor removing a missing one returns-1and does not incrementlatest_version(). - Exact bulk threshold (
total_qty == bulk_threshold): Uses>=, so hitting the threshold immediately reprices all units of that ingredient atbulk_price. - Dropping back below
bulk_thresholdonremove_recipeorcheckout: Subtracting a recipe's ingredients swaps the line cost back tobase_pricefor all remaining units. checkout(0)andcheckout(latest_version):checkout(0)empties the cart and resets version numbering so the next edit becomes1;checkout(latest_version)pops nothing and returnscurrent_cost.- Re-adding a removed
recipe_idwith different ingredients: Because each"remove"delta keeps a direct reference to the exactingredientsdict 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, orbool): RaisesValueErrorbefore modifying any state; checkingisinstance(version_id, bool)explicitly rejectsTrueandFalse(which subclassintin Python). - Floating-point rounding drift: Snapping
self.current_cost = self.version_costs[version_id]aftercheckoutand resetting0.0wheningredient_totalsbecomes 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
2and3flour must combine to5 >= 4and trigger bulk pricing together. - Charging
bulk_priceonly on units abovebulk_threshold: The specification charges every unit atbulk_priceoncetotal_qty >= bulk_threshold, not tiered marginal brackets. - Deep-copying
active_recipesoringredient_totalsper version: Violates the memory constraint and turnsO(k)mutations intoO(cart_size)copies. - Storing only
(action, recipe_id)in"remove"deltas without the removedingredientsdict: Makes it impossible to restore the recipe's quantities duringcheckout, or restores the wrong quantities if the samerecipe_idwas later re-added with modified ingredients. - Forgetting to truncate discarded versions on
checkout(v): Aftercheckout(1),get_total_cost(2)must raiseValueError, and the next successful edit must receive version ID2, not3. - 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
vstores(parent_id, delta, cost)andcheckout(target_v)never deletes nodes—instead, find the lowest common ancestor (LCA) (the deepest shared ancestor version of the current headuandtarget_v), walk upward fromuto the LCA undoing deltas, and walk downward from the LCA totarget_vreapplying deltas. Named branches are just abranch_name -> version_iddictionary, and merging branchBintoAcomparesAandBagainst their LCA, combining non-overlapping recipe additions/removals and raising a merge conflict if both branches added the samerecipe_idwith 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, storingversion_costs[v]already serves every historical read inO(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 everyKversions so any versionvis reconstructed by loading checkpoint(v // K) * Kand replaying at mostK - 1deltas (K / 2on average). Balancing snapshot memory(V / K) * C(for cart sizeC) against read replay workR * (K / 2) * k(forRreads) shrinks the optimal intervalKinversely withsqrt(R)—so100xmore reads calls for10xmore 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 inO(k log C)space per edit andO(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_costreaders to run concurrently while givingadd_recipe,remove_recipe, andcheckoutexclusive 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 version5is active right after Thread B checked out version2, add optimistic concurrency control—requiring mutations to passexpected_version_idand rejecting the call iflatest_version() != expected_version_idso the caller can refresh and retry cleanly.
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?
- 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?
- 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?
Similar questions
- Transactional Shopping Cart with Nested Scopes
- Batched Message Dispatcher with Individual Cooldown Retries
- Batched API Dispatch with Per-Item Cooldown Retries
- Cart State Management with Undo and Redo
- Optimal 3x3 Tic-Tac-Toe Solver via Backtracking
- Exclusive Function Runtime
More Decagon interview questions
- Enumerating Tic-Tac-Toe Move Sequences by Outcome Hard
- Game-Tree Enumeration for 4x4 Three-in-a-Row Medium
- Security Architecture for an External-Facing LLM Assistant Medium Pro
- Rolling-Window CSAT Score Tracker Easy Pro
- Cart State Management with Undo and Redo Medium Pro
- Optimal 3x3 Tic-Tac-Toe Solver via Backtracking Medium Pro
- Project Ownership, Lessons From a Setback, and Daily AI Judgment Medium Pro
- Transactional Shopping Cart with Nested Scopes Hard Pro
- Exclusive Function Runtime Medium Pro
- Batched Message Dispatcher with Individual Cooldown Retries Medium Pro