Find All Possible Recipes from Given Supplies — LeetCode 2115 Python Solution

MediumGraphTopological SortArrayHash TableString
Problem
#2115
Reading time
3 min

The problem

You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients.

Example

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".

Python solution

Python
class Solution:
    def findAllRecipes(
        self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]
    ) -> List[str]:
        g = defaultdict(list)
        indeg = defaultdict(int)
        for a, b in zip(recipes, ingredients):
            for v in b:
                g[v].append(a)
            indeg[a] += len(b)
        q = supplies
        ans = []
        for i in q:
            for j in g[i]:
                indeg[j] -= 1
                if indeg[j] == 0:
                    ans.append(j)
                    q.append(j)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Topological Sort

Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 2115. Find All Possible Recipes from Given Supplies is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.

The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2115. Find All Possible Recipes from Given Supplies?
LeetCode 2115. Find All Possible Recipes from Given Supplies is rated Medium on LeetCode.
What is the time complexity of LeetCode 2115. Find All Possible Recipes from Given Supplies?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2115. Find All Possible Recipes from Given Supplies?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2115. Find All Possible Recipes from Given Supplies cover?
LeetCode 2115. Find All Possible Recipes from Given Supplies is tagged Graph, Topological Sort, Array, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview