Find All Possible Recipes from Given Supplies — LeetCode 2115 Python Solution
MediumGraphTopological SortArrayHash TableString
- Problem
- #2115
- Pattern
- Topological Sort
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients.
Example
- Input
- recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]
- Output
- ["bread"]
- Explanation
- We can create "bread" since we have the ingredients "yeast" and "flour".
Python solution
Python
class Solution:
def findAllRecipes(
self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]
) -> List[str]:
g = defaultdict(list)
indeg = defaultdict(int)
for a, b in zip(recipes, ingredients):
for v in b:
g[v].append(a)
indeg[a] += len(b)
q = supplies
ans = []
for i in q:
for j in g[i]:
indeg[j] -= 1
if indeg[j] == 0:
ans.append(j)
q.append(j)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2115. Find All Possible Recipes from Given Supplies is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2115. Find All Possible Recipes from Given Supplies?
- LeetCode 2115. Find All Possible Recipes from Given Supplies is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2115. Find All Possible Recipes from Given Supplies?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2115. Find All Possible Recipes from Given Supplies?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2115. Find All Possible Recipes from Given Supplies cover?
- LeetCode 2115. Find All Possible Recipes from Given Supplies is tagged Graph, Topological Sort, Array, Hash Table and String on LeetCode.