Find All Possible Recipes from Given Supplies (LeetCode 2115): Solution and Explanation
Each recipe needs a list of ingredients, some of which are other recipes. Starting from an unlimited stock of supplies, return every recipe that can eventually be made.
Intuition
Draw an arrow from each ingredient to every recipe that uses it. A recipe becomes possible exactly when every arrow pointing into it starts at something you already have.
That is the setup of a topological sort. Keep a counter of missing ingredients for each recipe. Every time you gain an item, follow its arrows and lower those counters by one.
A recipe whose counter hits zero is made, and from then on it behaves like one more supply, so it goes back into the queue to unlock whatever depends on it. Recipes that sit on a cycle, or that need an item nobody has, never reach zero and are left out.
Approach: Kahn's algorithm from the supplies
- For each recipe set
need[r]to the number of its ingredients, and for each ingredientxappendrtousers[x]. - Put every supply in a queue.
- Pop an item. For each recipe
rinusers[item], decrementneed[r]. - If
need[r]becomes 0, addrto the answer and push it onto the queue. - When the queue is empty, return the answer.
Step-by-step example
recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]
- need = {bread: 2}. users = {yeast: [bread], flour: [bread]}.
- Queue = [yeast, flour, corn].
- Pop yeast: need[bread] drops to 1.
- Pop flour: need[bread] drops to 0, so bread is made and pushed onto the queue.
- Pop corn: no recipe uses it. Pop bread: no recipe uses it either.
- The queue is empty. Return ["bread"].
Code: Python, Java, C++
1class Solution:
2 def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:
3 need = {}
4 users = defaultdict(list)
5 for r, ing in zip(recipes, ingredients):
6 need[r] = len(ing)
7 for x in ing:
8 users[x].append(r)
9 queue = deque(supplies)
10 made = []
11 while queue:
12 item = queue.popleft()
13 for r in users[item]:
14 need[r] -= 1
15 if need[r] == 0:
16 made.append(r)
17 queue.append(r)
18 return made1class Solution {
2 public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {
3 Map<String, Integer> need = new HashMap<>();
4 Map<String, List<String>> users = new HashMap<>();
5 for (int i = 0; i < recipes.length; i++) {
6 need.put(recipes[i], ingredients.get(i).size());
7 for (String x : ingredients.get(i)) {
8 users.computeIfAbsent(x, key -> new ArrayList<>()).add(recipes[i]);
9 }
10 }
11 Deque<String> queue = new ArrayDeque<>(Arrays.asList(supplies));
12 List<String> made = new ArrayList<>();
13 while (!queue.isEmpty()) {
14 String item = queue.poll();
15 for (String r : users.getOrDefault(item, Collections.emptyList())) {
16 need.put(r, need.get(r) - 1);
17 if (need.get(r) == 0) {
18 made.add(r);
19 queue.offer(r);
20 }
21 }
22 }
23 return made;
24 }
25}1class Solution {
2public:
3 vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
4 unordered_map<string, int> need;
5 unordered_map<string, vector<string>> users;
6 for (int i = 0; i < (int)recipes.size(); i++) {
7 need[recipes[i]] = ingredients[i].size();
8 for (auto& x : ingredients[i]) {
9 users[x].push_back(recipes[i]);
10 }
11 }
12 queue<string> q;
13 for (auto& s : supplies) q.push(s);
14 vector<string> made;
15 while (!q.empty()) {
16 string item = q.front();
17 q.pop();
18 for (auto& r : users[item]) {
19 if (--need[r] == 0) {
20 made.push_back(r);
21 q.push(r);
22 }
23 }
24 }
25 return made;
26 }
27};Time and space complexity
O(S + I)
S is the number of supplies and recipes that pass through the queue, and I is the total number of ingredient entries. Each item is popped once and each ingredient edge is followed once.
O(S + I)
The counters, the users lists and the queue together hold every item and every ingredient edge once.
Other approaches
DFS with memo and cycle marks (time O(S + I), space O(S + I))
For each recipe, recursively check that every ingredient is a supply or a makeable recipe. Mark recipes as visiting, makeable or impossible so cycles are detected and each recipe is solved once.
Repeated passes (time O(n * I), space O(S))
Loop over all recipes again and again, making any recipe whose ingredients are all available, until a full pass makes nothing new. Simple, but it can take n passes.
Common mistakes
- Forgetting to push a newly made recipe onto the queue. Recipes that need other recipes are then never unlocked.
- Using plain recursion without cycle detection. Two recipes that need each other recurse forever.
- Checking only the supplies list for ingredients. An ingredient may be a recipe made later.
- Indexing users by recipe position instead of ingredient name, which breaks when the same ingredient feeds several recipes.
Frequently asked questions
Why does a recipe on a cycle never get made?
Each recipe on the cycle waits for the previous one. None of them can be the first to reach a counter of zero, so none is ever pushed onto the queue.
Does the order of the answer matter?
No. Any order is accepted. The queue order produced here is simply the order in which recipes became ready.
What if a recipe uses an ingredient that is neither a supply nor a recipe?
Nothing ever decrements that edge, so the counter stays above zero and the recipe, plus anything that depends on it, is left out.
How is this related to Course Schedule?
It is the same in-degree counting. Courses become recipes, prerequisites become ingredients, and supplies are the courses with no prerequisites.