Solving Leetcode Interviews in Seconds with AI: Find All Possible Recipes from Given Supplies
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2115" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. A recipe can also be an ingredient for other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients. Example 1: 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". Example 2: Input: recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". Example 3: Input: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"] Output: ["bread","sandwich","burger"] Explanation: We can create "bread" since we have the ingredients "yeast" and "flour". We can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread". We can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich". Constraints: n == recipes.length == ingredients.length 1 <= n <= 100 1 <= ingredients[i].length, supplies.length <= 100 1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10 recipes[i], ingredients[i][j], and supplies[k] consist only of lowercase English letters. All the values of recipes and supplies combined are unique. Each ingredients[i] does not contain any duplicate values.
Explanation
Here's the solution, broken down for clarity:
Key Idea: Use topological sort. Represent the recipes and ingredients as a directed graph. A recipe depends on its ingredients. Start with recipes that can be made using the initial supplies. Add these to the set of supplies and repeat.
Approach:
- Build a graph where nodes are recipes and edges represent dependencies (ingredients needed).
- Keep track of the in-degree of each recipe (number of missing ingredients).
- Use a queue to store recipes that can be made (in-degree 0).
- Process the queue: reduce the in-degree of dependent recipes and add them to the queue if their in-degree becomes 0.
Complexity:
- Runtime: O(n + m), where n is the total number of recipes and ingredients, and m is the total number of ingredient dependencies.
- Storage: O(n + m) to store the graph, in-degrees, and other data structures.
Code
from collections import defaultdict, deque
def canMakeRecipes(recipes, ingredients, supplies):
"""
Finds and returns a list of recipes that can be created from the given ingredients and supplies.
Args:
recipes (List[str]): A list of recipe names.
ingredients (List[List[str]]): A 2D list of ingredients required for each recipe.
supplies (List[str]): A list of initial supplies.
Returns:
List[str]: A list of recipes that can be created.
"""
graph = defaultdict(list) # Adjacency list representing the graph
in_degree = {} # In-degree of each recipe
recipe_index = {recipe: i for i, recipe in enumerate(recipes)} # Map recipe name to index
# Initialize in-degree for each recipe
for recipe in recipes:
in_degree[recipe] = 0
# Build the graph and calculate in-degrees
for i, recipe in enumerate(recipes):
for ingredient in ingredients[i]:
if ingredient in recipe_index:
graph[ingredient].append(recipe) # Ingredient is a recipe itself
in_degree[recipe] += 1
elif ingredient not in supplies:
in_degree[recipe] += 1 # Missing ingredient, cannot make recipe yet
# Initialize queue with recipes that have no dependencies (in-degree 0)
queue = deque([recipe for recipe in recipes if in_degree[recipe] == 0])
result = []
while queue:
recipe = queue.popleft()
result.append(recipe)
for neighbor in graph[recipe]:
in_degree[neighbor] -= 1
if in_degree[neighbor] == 0:
queue.append(neighbor)
return result