#2115
Find All Possible Recipes from Given Supplies
MediumArrayHash TableStringGraph TheoryTopological SortHash MapGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
The optimal approach uses a graph-like structure to track dependencies between recipes and ingredients. We can use a queue to process recipes that can be created once their ingredients are available, allowing us to efficiently determine all possible recipes.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping of recipes to their ingredients and a count of how many ingredients each recipe needs.
- 2Step 2: Use a set to keep track of available supplies and initialize a queue with the supplies.
- 3Step 3: While the queue is not empty, check if any recipes can be created with the current supplies, adding them to the available supplies and the result list.
solution.py21 lines
1from collections import defaultdict, deque
2
3def findAllRecipes(recipes, ingredients, supplies):
4 supply_set = set(supplies)
5 recipe_map = defaultdict(list)
6 indegree = defaultdict(int)
7 for i, recipe in enumerate(recipes):
8 indegree[recipe] = len(ingredients[i])
9 for ingredient in ingredients[i]:
10 recipe_map[ingredient].append(recipe)
11 queue = deque(supplies)
12 result = []
13 while queue:
14 current_supply = queue.popleft()
15 if current_supply in recipe_map:
16 for recipe in recipe_map[current_supply]:
17 indegree[recipe] -= 1
18 if indegree[recipe] == 0:
19 result.append(recipe)
20 queue.append(recipe)
21 return resultℹ
Complexity note: This complexity is due to processing each recipe and ingredient once, where n is the number of recipes and m is the total number of ingredients across all recipes.
- 1Understanding dependencies between recipes and ingredients is crucial.
- 2Using a graph-like approach can simplify the problem of tracking which recipes can be created.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.