Skip to content

Commit 569f60d

Browse files
authored
Create Find All Possible Recipes from Given Supplies.java
1 parent 44df3cb commit 569f60d

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients,
3+
String[] supplies) {
4+
Map<String, Set<String>> ingredientToRecipeMap = new HashMap<>();
5+
Map<String, Integer> recipeToIngredientCount = new HashMap<>();
6+
for (int i = 0; i < recipes.length; i++) {
7+
String recipe = recipes[i];
8+
List<String> ingredientsForRecipe = ingredients.get(i);
9+
recipeToIngredientCount.put(recipe, ingredientsForRecipe.size());
10+
for (String ingredient : ingredientsForRecipe) {
11+
ingredientToRecipeMap.computeIfAbsent(ingredient, k -> new HashSet<>()).add(recipe);
12+
}
13+
}
14+
Queue<String> queue = new LinkedList<>(List.of(supplies));
15+
Set<String> result = new HashSet<>();
16+
while (!queue.isEmpty()) {
17+
String ingredient = queue.remove();
18+
for (String dependentRecipe : ingredientToRecipeMap.getOrDefault(ingredient,
19+
new HashSet<>())) {
20+
recipeToIngredientCount.put(dependentRecipe,
21+
recipeToIngredientCount.get(dependentRecipe) - 1);
22+
if (recipeToIngredientCount.get(dependentRecipe) == 0) {
23+
result.add(dependentRecipe);
24+
queue.add(dependentRecipe);
25+
}
26+
}
27+
}
28+
return new ArrayList<>(result);
29+
}
30+
}

0 commit comments

Comments
 (0)