Skip to content

Commit 04c96f8

Browse files
authored
Update Find All Possible Recipes from Given Supplies.java
1 parent 27848c9 commit 04c96f8

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed
Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,29 @@
11
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<>();
2+
public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) {
3+
Map<String, List<String>> map = new HashMap<>();
4+
Map<String, Integer> ingredientCounter = new HashMap<>();
65
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);
6+
List<String> currentIngredientList = ingredients.get(i);
7+
for (String ingredient : currentIngredientList) {
8+
map.computeIfAbsent(ingredient, k -> new ArrayList<>()).add(recipes[i]);
9+
ingredientCounter.put(recipes[i], ingredientCounter.getOrDefault(recipes[i], 0) + 1);
1210
}
1311
}
14-
Queue<String> queue = new LinkedList<>(List.of(supplies));
15-
Set<String> result = new HashSet<>();
12+
Queue<String> queue = new LinkedList<>();
13+
Set<String> prepared = new HashSet<>();
14+
for (String supply : supplies) {
15+
queue.add(supply);
16+
}
1617
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);
18+
String removed = queue.remove();
19+
for (String dependentRecipe : map.getOrDefault(removed, new ArrayList<>())) {
20+
ingredientCounter.put(dependentRecipe, ingredientCounter.getOrDefault(dependentRecipe, 0) - 1);
21+
if (ingredientCounter.get(dependentRecipe) == 0) {
2422
queue.add(dependentRecipe);
23+
prepared.add(dependentRecipe);
2524
}
2625
}
2726
}
28-
return new ArrayList<>(result);
27+
return new ArrayList<>(prepared);
2928
}
3029
}

0 commit comments

Comments
 (0)