Build an Inventory Manager with Nested Recipe Expansion
Data Structure DesignModel answerLast updated
Implement a service that models recipes with nested dependencies, validates acyclic graphs, and atomically decrements raw inventory when orders succeed.
You are building an inventory management system for a kitchen service. The system tracks recipes, raw materials, and fulfillment of orders. Each recipe has a name, a preparation duration, and a list of ingredients with quantities. An ingredient can be either a raw material or another recipe, allowing nested composition.
When an order is placed for a recipe, the system must:
- Recursively expand all nested recipes to determine the total raw materials needed
- Verify that sufficient inventory exists for every raw material
- Atomically decrement all required inventory counts, or leave inventory unchanged if any requirement cannot be met
Your task is to design the core data structures and methods for this system, addressing the following:
Part 1: Core Model
Define classes and methods to represent recipes, raw materials, and inventory. Your design should support:
- Adding a new recipe with a name, preparation time (in minutes), and ingredient list
- Adding or updating raw material inventory counts
- Placing an order for a recipe by name
- Querying recipes by preparation time threshold
Specify how your design handles:
- Unique naming for recipes and materials
- Validation of quantities (recipes require positive ingredient amounts; inventory is non-negative)
- Distinguishing between raw materials and recipe references in ingredient lists
- Behavior when a recipe or material name already exists
Part 2: Dependency Resolution
Explain how your system expands nested recipes and detects invalid states:
- Identifying missing recipe or material references
- Detecting cycles in the recipe dependency graph (direct or indirect)
- Aggregating quantities when the same raw material appears through multiple paths
- Handling integer overflow when multiplying or summing quantities
Part 3: Atomic Order Fulfillment
Design the order placement logic to ensure atomicity:
- Calculate total raw material requirements before modifying inventory
- Ensure all-or-nothing updates: either all inventory decrements succeed or none do
- Handle concurrent order requests safely
- Return success or failure with clear semantics
Part 4: Query Interface and Testing
Define query methods and describe key test scenarios:
- List recipes with preparation time above a given threshold (specify whether inclusive or exclusive)
- Ensure returned collections are immutable or defensive copies
- Outline tests for nested expansion, cycle detection, exact inventory matches, insufficient stock, and concurrent orders
Hints
Hint 1
Use separate types or enums to distinguish raw material references from recipe references in ingredient lists.
Hint 2
Cycle detection can use depth-first search with a recursion stack, checking each recipe only once per traversal.
Hint 3
Expand the full raw material requirement map before checking any inventory levels, then verify all counts before decrementing any.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A strong solution defines clear types with validation, detects cycles during expansion, aggregates raw requirements correctly, and uses locking or transactions to ensure atomic inventory updates.
Part 1: Core Model
Classes and Fields
class Recipe {
private final String name;
private final int prepTimeMinutes;
private final Map<IngredientRef, Integer> ingredients; // immutable
// Constructor validates positive prepTime and quantities
}
interface IngredientRef {}
class RawMaterialRef implements IngredientRef {
private final String materialName;
}
class RecipeRef implements IngredientRef {
private final String recipeName;
}
class InventoryService {
private final Map<String, Recipe> recipes = new HashMap<>();
private final Map<String, Integer> stock = new HashMap<>();
private final ReentrantLock lock = new ReentrantLock();
}
Key Methods
addRecipe(String name, int prepTime, Map<IngredientRef, Integer> ingredients): Validates positive prep time and quantities, replaces any existing recipe with the same name.addStock(String material, int count): Sets inventory for a raw material (replaces existing count).boolean placeOrder(String recipeName): Returns true and decrements inventory atomically if successful, false otherwise with no changes.List<String> getRecipesAbove(int thresholdMinutes): Returns recipe names with prep time strictly greater than the threshold, sorted alphabetically.
Invariants
- Recipe and material names are case-sensitive unique identifiers.
- Ingredient quantities in recipes must be positive integers.
- Stock counts are non-negative.
- Methods return immutable views or defensive copies to prevent external mutation.
Part 2: Dependency Resolution
Cycle Detection
Use depth-first traversal with a recursion stack. Maintain two sets: one for visited recipes (to avoid re-expansion) and one for the current path (to detect back edges).
private boolean hasCycle(String recipeName, Set<String> visited, Set<String> recStack) {
if (recStack.contains(recipeName)) return true;
if (visited.contains(recipeName)) return false;
Recipe recipe = recipes.get(recipeName);
if (recipe == null) return false; // missing reference handled separately
visited.add(recipeName);
recStack.add(recipeName);
for (IngredientRef ref : recipe.getIngredients().keySet()) {
if (ref instanceof RecipeRef) {
if (hasCycle(((RecipeRef) ref).getRecipeName(), visited, recStack)) {
return true;
}
}
}
recStack.remove(recipeName);
return false;
}
Expansion and Aggregation
Recursively multiply quantities through each path and aggregate into a single raw-material map:
private Map<String, Long> expandToRaw(String recipeName) {
Map<String, Long> totals = new HashMap<>();
expandHelper(recipeName, 1L, totals);
return totals;
}
private void expandHelper(String recipeName, long multiplier, Map<String, Long> totals) {
Recipe recipe = recipes.get(recipeName);
for (Map.Entry<IngredientRef, Integer> entry : recipe.getIngredients().entrySet()) {
long needed = (long) entry.getValue() * multiplier;
if (entry.getKey() instanceof RawMaterialRef) {
String material = ((RawMaterialRef) entry.getKey()).getMaterialName();
totals.merge(material, needed, Long::sum);
} else {
String nestedRecipe = ((RecipeRef) entry.getKey()).getRecipeName();
expandHelper(nestedRecipe, needed, totals);
}
}
}
Overflow Handling
Use long for intermediate arithmetic. Before returning or checking stock, verify each aggregated quantity fits in an int and does not exceed Integer.MAX_VALUE. If overflow is detected, treat it as a validation failure.
Memoization
Cache expanded raw requirements per recipe after the first expansion, invalidating the cache when a recipe is replaced.
Part 3: Atomic Order Fulfillment
Two-Phase Check-and-Decrement
- Expand the recipe to raw requirements.
- Check that every required material has sufficient stock.
- If all checks pass, decrement all inventory atomically.
public boolean placeOrder(String recipeName) {
lock.lock();
try {
Recipe recipe = recipes.get(recipeName);
if (recipe == null) return false;
if (hasCycle(recipeName, new HashSet<>(), new HashSet<>())) {
return false;
}
Map<String, Long> required = expandToRaw(recipeName);
// Check overflow
for (long qty : required.values()) {
if (qty > Integer.MAX_VALUE) return false;
}
// Check sufficiency
for (Map.Entry<String, Long> entry : required.entrySet()) {
int available = stock.getOrDefault(entry.getKey(), 0);
if (available < entry.getValue()) {
return false;
}
}
// Decrement atomically
for (Map.Entry<String, Long> entry : required.entrySet()) {
stock.put(entry.getKey(), stock.get(entry.getKey()) - entry.getValue().intValue());
}
return true;
} finally {
lock.unlock();
}
}
Concurrency
A single coarse-grained lock protects both recipe and stock maps, ensuring no race conditions during check-and-decrement. For higher throughput, consider read-write locks or optimistic concurrency with version numbers.
Part 4: Query Interface and Testing
Query Method
public List<String> getRecipesAbove(int thresholdMinutes) {
lock.lock();
try {
return recipes.values().stream()
.filter(r -> r.getPrepTime() > thresholdMinutes)
.map(Recipe::getName)
.sorted()
.collect(Collectors.toUnmodifiableList());
} finally {
lock.unlock();
}
}
The comparison is strict (>), and results are sorted alphabetically for determinism.
Key Tests
- Nested expansion: Recipe A uses Recipe B, which uses raw material X; verify correct quantity multiplication.
- Shared ingredients: A uses B and C, both requiring X; verify aggregation.
- Cycle detection: A uses B, B uses C, C uses A; order returns false.
- Missing reference: A uses non-existent Recipe D; order returns false.
- Exact stock: Order requires exactly available stock; succeeds and leaves zero.
- Insufficient stock: Order requires more than available; returns false, stock unchanged.
- Concurrent orders: Two threads order simultaneously; verify total decrements match successful orders.
- Overflow: Nested multiplication exceeds
Integer.MAX_VALUE; order returns false. - Recipe replacement: Replace a recipe, verify old expansion no longer applies.
- Stock replenishment: Add stock after a failed order, verify subsequent order succeeds.
Complexity
- Time:
O(V + E)for cycle detection per order, where V is recipes and E is ingredient edges. Expansion is linear in the size of the dependency subgraph. - Space:
O(V)for recursion stack and aggregation map.
Common Mistakes
- Forgetting to validate acyclicity before expansion, leading to infinite loops.
- Checking and decrementing stock incrementally instead of atomically.
- Using
intarithmetic without overflow checks. - Returning mutable references to internal recipe or stock maps.
- Summing nested preparation times instead of using the stored value per recipe.