Find All Possible Recipes from Given Supplies

Medium · Graphs · Array · Hash Table · String · Graph · Topological Sort

Problem

You know how to cook n recipes. Recipe recipes[i] needs every item listed in ingredients[i]. An ingredient may itself be one of the recipes, in which case that recipe must be cooked first. You also start with an unlimited amount of every item in supplies.

Return the names of all recipes you are able to cook, in any order. Recipes may depend on each other, even in a cycle; a recipe caught in a cycle can never be made.

Examples

Input: recipes = ["toast","sandwich"], ingredients = [["bread"],["toast","cheese"]], supplies = ["bread","cheese"]
Output: ["toast","sandwich"]

Toast needs only bread. Once toast exists, the sandwich can be made too.

Input: recipes = ["soup"], ingredients = [["water","salt"]], supplies = ["water"]
Output: []

There is no salt anywhere.

Input: recipes = ["ab","cd"], ingredients = [["cd"],["ab"]], supplies = []
Output: []

Each recipe needs the other, so neither can be started.

Constraints

Approaches

Follow-up

What if a supply can run out, say each supply has a limited count and each recipe uses one of each ingredient? Then cooking order matters and choices compete for the same items: it stops being a reachability question and becomes a search or flow problem.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…