State-Tracked Recipe Basket with Bulk Pricing
Data Structure DesignAuto-graded · 13 test casesLast updated
Simulate a versioned basket engine that aggregates multi-recipe component quantities for bulk discount calculations, supporting mutations and rollback operations.
You are building an execution engine for an interactive meal plan basket. Users modify their basket by adding or removing recipes. Each recipe consists of a dictionary mapping item names to their required quantities.
Because different recipes can share the same item (e.g., both require "garlic"), the basket aggregates item totals across all active recipes to determine whether bulk tier pricing applies.
Pricing Rules
Every component in ingredient_catalog is configured with three properties:
base_price(float): Cost per unit when the aggregated quantity across all recipes is strictly less thanbulk_threshold.bulk_threshold(int): Minimum total count of this item needed in the basket to qualify for bulk pricing.bulk_price(float): Cost per unit when the aggregated quantity across all recipes is $\ge$bulk_threshold.
Versioning Rules
- The basket starts at version
0(empty basket). - Every successful
add_recipeorremove_recipeoperation creates a new incremented version ID (1, 2, 3, ...). - Failed additions or removals (e.g., adding a recipe already present, or removing a non-existent recipe) return
-1and do not generate a new version. get_total_costcomputes the monetary value of a specified version without altering state. If no version is specified (orNoneis passed), it computes the price for the latest active version.checkoutrolls back the state to the requested version ID: any versions created after that target version are permanently discarded, and the target version becomes the current head version. It returns the calculated cost at that restored state.- If a query references an invalid version ID (e.g., negative, non-integer, or strictly greater than the highest current version ID), the method records the string
'ValueError'as its output instead of throwing an unhandled runtime error.
Input Parameters
ingredient_catalog: A dict mapping item names to their pricing dictionary ({"base_price": float, "bulk_threshold": int, "bulk_price": float}).operations: A list of operation strings, where each entry is one of"add_recipe","remove_recipe","get_total_cost", or"checkout".arguments: A list of argument lists corresponding to each operation:"add_recipe":[recipe_id: str, ingredients: dict[str, int]]"remove_recipe":[recipe_id: str]"get_total_cost":[version_id: int]or[](defaults to latest version if omitted or[None])"checkout":[version_id: int]
Constraints
- $0 \le \text{len(operations)} \le 1000$
- Full copying (deep snapshotting) of the basket state on every single version mutation is avoided; version tracking should store structural deltas or efficient logs.
- Item quantities inside recipes are positive integers.
Examples
Example 1
Input: versioned_recipe_cart({'garlic': {'base_price': 1, 'bulk_threshold': 5, 'bulk_price': 0.6}, 'chicken': {'base_price': 8, 'bulk_threshold': 2, 'bulk_price': 7}}, ['add_recipe', 'get_total_cost', 'add_recipe', 'get_total_cost', 'checkout', 'get_total_cost'], [['curry', {'garlic': 3, 'chicken': 1}], [1], ['roast', {'garlic': 3, 'chicken': 1}], [], [1], [2]])
Output: [1, 11, 2, 17.6, 11, 'ValueError']
Hints
Hint 1
Avoid deep-copying the entire basket map on every operation to satisfy memory efficiency expectations.
Hint 2
Track an ordered list of changes (deltas) where each entry records a recipe addition or removal relative to the previous version.
Hint 3
When rolling back via `checkout(v)`, truncate your change log so that version `v` becomes the latest point, discarding subsequent change records.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To implement a space-efficient versioned shopping cart system without storing full snapshot copies of all active recipes on every operation:
-
Active State & Change Log (Delta Log):
- We maintain a primary map
recipesfor the current live head of the basket. This allows $O(1)$ validation when checking if a recipe exists before adding or removing it. - We record a incremental log
deltaswhere index $i$ stores the mutation converting version $i$ into version $i+1$. Each entry stores(recipe_id, ingredient_map)for additions, or(recipe_id, None)for removals.
- We maintain a primary map
-
Reconstructing Historical States:
- To find the contents of version $v$, we iterate through
deltas[:v]starting from an empty dict. - Applying these deltas sequentially constructs the exact dictionary of recipes that were active at version $v$.
- To find the contents of version $v$, we iterate through
-
Pricing Strategy:
- Once the recipe mapping for a given version is established, we iterate over all recipes to sum the overall quantity of each ingredient item.
- For each item present, we compare its aggregated count against its catalog entry's
bulk_threshold. If the count meets or exceeds the threshold, we multiply the total units bybulk_price; otherwise, we multiply bybase_price.
-
Handling Checkout:
- When a user checks out version $v$, all mutations past $v$ are discarded. We truncate
deltasto length $v$, rebuild the liverecipesmapping at version $v$, and calculate the total cost at this newly restored active head.
- When a user checks out version $v$, all mutations past $v$ are discarded. We truncate
-
Error & Validation Rules:
- Invalid versions (e.g., negative numbers, floats, or values exceeding
len(deltas)) report'ValueError'in the returned output array. - Attempting to add a recipe that already exists or remove a recipe that isn't present returns
-1without incrementing the version counter.
- Invalid versions (e.g., negative numbers, floats, or values exceeding
Complexity Analysis
- Time Complexity:
add_recipe: $O(K)$, where $K$ is the number of distinct ingredients in the added recipe.remove_recipe: $O(1)$.get_total_cost: $O(V + C)$, where $V$ is the version index and $C$ is the total count of ingredient entries across active recipes at version $v$.checkout: $O(V + C)$, to slice log history, rebuild active map, and aggregate costs.
- Space Complexity: $O(U)$, where $U$ is the total number of unique recipe delta additions stored in the change log.
from typing import Dict, List
def versioned_recipe_cart(ingredient_catalog: Dict[str, Dict], operations: List[str], arguments: List[List]) -> List:
recipes = {}
deltas = []
results = []
def cart_at(version):
cart = {}
for recipe_id, ingredients in deltas[:version]:
if ingredients is None:
cart.pop(recipe_id, None)
else:
cart[recipe_id] = ingredients
return cart
def cost(cart):
totals = {}
for ingredients in cart.values():
for name, quantity in ingredients.items():
totals[name] = totals.get(name, 0) + quantity
total = 0.0
for name, quantity in totals.items():
rule = ingredient_catalog[name]
price = rule['bulk_price'] if quantity >= rule['bulk_threshold'] else rule['base_price']
total += quantity * price
return total
for operation, args in zip(operations, arguments):
if operation == 'add_recipe':
recipe_id, ingredients = args
if recipe_id in recipes:
results.append(-1)
else:
ingredients = dict(ingredients)
recipes[recipe_id] = ingredients
deltas.append((recipe_id, ingredients))
results.append(len(deltas))
elif operation == 'remove_recipe':
recipe_id = args[0]
if recipe_id not in recipes:
results.append(-1)
else:
del recipes[recipe_id]
deltas.append((recipe_id, None))
results.append(len(deltas))
elif operation == 'get_total_cost':
version = args[0] if args else None
if version is None:
version = len(deltas)
if not isinstance(version, int) or version < 0 or version > len(deltas):
results.append('ValueError')
else:
results.append(cost(cart_at(version)))
elif operation == 'checkout':
version = args[0]
if not isinstance(version, int) or version < 0 or version > len(deltas):
results.append('ValueError')
else:
deltas = deltas[:version]
recipes = cart_at(version)
results.append(cost(recipes))
else:
raise ValueError('Unknown operation')
return results