Find All Possible Recipes from Given Supplies
Explore how to apply topological sort to identify all recipes you can create from given supplies and ingredient dependencies. Understand how to manage recipe interdependencies, detect cycles, and efficiently solve this problem in coding interviews.
We'll cover the following...
Statement
You are given information about recipes, and its corresponding ingredients are provided in the 2D array ingredients. The recipes[i], can be prepared if all the necessary ingredients listed in ingredients[i] are available. Some ingredients might need to be created from other recipes, meaning ingredients[i] may contain strings that are also in recipes.
Additionally, you have a string array supplies that contains all the ingredients you initially have, and you have an infinite supply of each.
Return a list of all the recipes you can create. The answer can be returned in any order.
Note: It is possible for two recipes to list each other as ingredients. However, if these are the only two recipes provided, the expected output is an empty list.
Constraints:
nrecipes.lengthingredients.lengthningredients[i].length,supplies.lengthrecipes[i].length,ingredients[i][j].length,supplies[k].lengthrecipes[i],ingredients[i][j], andsupplies[k]consist only of lowercase English letters.All the combined values of
recipesandsuppliesare unique.Each
ingredients[i]doesn’t contain any duplicate values.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Find All Possible Recipes from Given Supplies
What is the output if the following lists are given as input?
recipes = [“soup”, “spaghetti”]
ingredients = [[“meat”, “yogurt”, “sauce”], [“pasta”, “salt”, “sauce”]]
supplies = [“meat”, “pasta”, “yogurt”, “sauce”]
[“soup”, “spaghetti”]
[“spaghetti”]
[“soup”]
[]
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground.
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(V + E) time and takes O(V + E) space. You may try to translate the logic of the solved puzzle into a coded solution.
def find_recipes(recipes, ingredients, supplies):# Replace this placeholder return statement with your codereturn []