{"id":"find-all-possible-recipes-from-given-supplies","title":"Find All Possible Recipes from Given Supplies","difficulty":"medium","patterns":["topological-sort"],"primaryConcept":"graph-toposort-ordering","concepts":["graph-toposort-ordering"],"problemForm":"core","companies":["Google","Amazon","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"unordered-array","syntheticTestConfig":{"inputShape":"recipe-dependencies","primaryParam":"recipes","sizeMetric":"nodes-plus-edges"},"description":"You are given recipe names, the ingredients each recipe needs, and a list of initial supplies.\n\nA recipe can be made when every ingredient it needs is either already in `supplies` or is another recipe that can be made first.\n\nReturn all recipes that can be made.","examples":[{"input":"recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]","output":"[\"bread\"]","explanation":"Both ingredients for bread are already available."},{"input":"recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]","output":"[\"bread\",\"sandwich\"]","explanation":"Bread can be made first, which unlocks sandwich."},{"input":"recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]","output":"[\"bread\",\"sandwich\",\"burger\"]","explanation":"The available supplies unlock bread, then sandwich, then burger."}],"constraints":[{"id":"1-len-recipes-100","text":"1 <= len(recipes) <= 100","check":{"kind":"sizeRange","target":"recipes","measure":"arrayLength","min":1,"max":100}},{"id":"1-len-ingredients-i-100","text":"1 <= len(ingredients[i]) <= 100","check":{"kind":"valueRange","target":"ingredients","selector":"arrayItemLengths","min":1,"max":100}},{"id":"1-len-supplies-100","text":"1 <= len(supplies) <= 100","check":{"kind":"sizeRange","target":"supplies","measure":"arrayLength","min":1,"max":100}},{"id":"recipes-i-ingredients-i-j-and-supplies-k-consist-of-lowercase-en","text":"recipes[i], ingredients[i][j], and supplies[k] consist of lowercase English letters","check":[{"kind":"domain","target":"recipes","selector":"nestedStringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]},{"kind":"domain","target":"ingredients","selector":"nestedStringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]},{"kind":"domain","target":"supplies","selector":"nestedStringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}]},{"id":"all-recipe-names-are-unique","text":"All recipe names are unique","check":{"kind":"uniqueness","target":"recipes","selector":"items"}},{"id":"ingredients-length-recipes-length","text":"len(ingredients) == len(recipes)","check":{"kind":"sizeRange","target":"ingredients","measure":"arrayLength","min":{"sizeOfInput":"recipes","measure":"arrayLength"},"max":{"sizeOfInput":"recipes","measure":"arrayLength"}}}],"starterCode":"class Solution:\n    def findAllRecipes(self, recipes: list[str], ingredients: list[list[str]], supplies: list[str]) -> list[str]:\n        # Your code here\n        pass","functionName":"findAllRecipes","testCases":[{"id":"1","input":{"recipes":["bread"],"ingredients":[["yeast","flour"]],"supplies":["yeast","flour","corn"]},"expected":["bread"],"description":"All ingredients are initial supplies."},{"id":"2","input":{"recipes":["bread","sandwich"],"ingredients":[["yeast","flour"],["bread","meat"]],"supplies":["yeast","flour","meat"]},"expected":["bread","sandwich"],"description":"One recipe unlocks another recipe."},{"id":"3","input":{"recipes":["bread","sandwich","burger"],"ingredients":[["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]],"supplies":["yeast","flour","meat"]},"expected":["bread","sandwich","burger"],"description":"A chain of recipes unlocks a later recipe."},{"id":"4","input":{"recipes":["soup","stew"],"ingredients":[["water","salt"],["soup","beef"]],"supplies":["water","beef"]},"expected":[],"description":"A missing base ingredient blocks every dependent recipe."},{"id":"5","input":{"recipes":["a","b","c"],"ingredients":[["b"],["a"],["flour"]],"supplies":["flour"]},"expected":["c"],"description":"A cycle between recipes stays blocked while an independent recipe succeeds."},{"id":"h1","input":{"recipes":["cake","frosting","layered"],"ingredients":[["flour","egg"],["sugar","milk"],["cake","frosting"]],"supplies":["flour","egg","sugar","milk"]},"expected":["cake","frosting","layered"],"description":"Two independent recipes jointly unlock a final recipe."},{"id":"h2","input":{"recipes":["x","y","z"],"ingredients":[["y"],["z"],["x"]],"supplies":["salt"]},"expected":[],"description":"A closed recipe cycle cannot start from unrelated supplies."},{"id":"h3","input":{"recipes":["tea","latte","brunch"],"ingredients":[["water","leaf"],["milk","coffee"],["tea","latte","toast"]],"supplies":["water","leaf","milk","coffee","toast"]},"expected":["tea","latte","brunch"],"description":"Multiple initial zero in-degree recipes are processed before their dependent recipe."},{"id":"h4","input":{"recipes":["dough","pizza","party"],"ingredients":[["flour","water"],["dough","cheese"],["pizza","drink"]],"supplies":["flour","water","cheese","drink"]},"expected":["dough","pizza","party"],"description":"One recipe chain unlocks the next recipe in sequence."},{"id":"h5","input":{"recipes":["a","b","cake"],"ingredients":[["b"],["a"],["flour"]],"supplies":["flour"]},"expected":["cake"],"description":"A blocked cycle leaves only the independent recipe available."},{"id":"topup-1","input":{"recipes":["sauce","pasta","dinner","dessert"],"ingredients":[["tomato","salt"],["flour","water"],["pasta","sauce"],["sugar","cream"]],"supplies":["tomato","salt","flour","water","sugar"]},"expected":["sauce","pasta","dinner"],"description":"Top-up case 1: two independent recipes unlock a meal while one recipe stays blocked by a missing supply."},{"id":"topup-2","input":{"recipes":["base","middle","top","loopa","loopb"],"ingredients":[["seed"],["base"],["middle"],["loopb","base"],["loopa"]],"supplies":["seed"]},"expected":["base","middle","top"],"description":"Top-up case 2: a valid chain should complete while a dependent recipe cycle remains blocked."}],"hints":[{"level":1,"content":"A recipe becomes available only after all of its missing ingredients have been resolved.","revealPattern":false},{"level":2,"content":"Treat each unavailable ingredient as pointing to the recipes waiting on it, and count how many missing ingredients remain for each recipe.","revealPattern":true},{"level":3,"content":"Use Kahn's algorithm: start with recipes whose missing count is zero, then each completed recipe reduces the count for recipes that depend on it.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"find-all-possible-recipes-from-given-supplies-2026-11-20-one-kitchen-counts-and-waiting-lists","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we build?","decisionPrompt":"Compare how many times each approach reads a recipe's ingredient list.","approaches":[{"id":"kahn-missing-count","name":"Missing counts and waiting lists","summary":"Give every recipe a count of its ingredients that are not among the supplies, and keep for each such ingredient the recipes waiting on it. Make the recipes at 0, lowering the counts of the recipes that were waiting.","decisionReason":"Each ingredient list is read once and each waiting link is followed at most once, so r recipes with e ingredient entries and s supplies take O(r + e + s) time and space.","complexity":{"time":"O(r + e + s)","space":"O(r + e + s)"},"tradeoffs":["Needs a count per recipe and a waiting list per missing ingredient."],"isOptimal":true},{"id":"repeated-rescans","name":"Repeated sweeps","summary":"Sweep the whole recipe list, making any recipe whose ingredients are all available, and repeat until a sweep makes nothing new.","decisionReason":"A chain where each recipe is listed before the one it needs gets one recipe made per sweep, so r recipes can take r sweeps that each visit every recipe and reread its list: O(r * (r + e)).","complexity":{"time":"O(r * (r + e))","space":"O(r + s)"},"tradeoffs":["Keeps only the set of available items, but reads the same lists again on every sweep."],"isOptimal":false},{"id":"supplies-only","name":"Check against the supplies only","summary":"Accept a recipe only when every ingredient it lists is among the supplies.","decisionReason":"taco needs slaw and mayo, which are recipes. A check against the supplies alone never treats them as available, so slaw and taco would be left out.","complexity":{"time":"O(e + s)","space":"O(s)"},"tradeoffs":["One pass, but a recipe that needs another recipe is always rejected."],"isOptimal":false}]},"codingCheckpoints":[{"id":"build-graph","title":"Start the waiting lists","description":"Create an empty map from an ingredient to the recipes that are waiting on it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create the adjacency map that points each blocked ingredient at the recipes depending on it.","doneWhen":"This step is done when an empty adjacency container exists to hold ingredient to dependent-recipe links before the scan runs.","shouldFailWhen":"This step should fail if links run from recipe to ingredient instead of ingredient to recipe.","roles":["unlock map","available supplies","blocked ingredient"],"mustProve":["An adjacency container is created to map an ingredient to the recipes waiting on it."],"mustNotAccept":["Storing edges only from a recipe to its ingredients.","Skipping the ingredient to dependent-recipe direction."]},"commonMistakes":["Keying the map by recipe, which only answers what that recipe needs"],"hint":"The lookup starts from the thing that was just made, so the ingredient is the key."},{"id":"calculate-indegree","title":"Give every recipe a missing count","description":"Before any ingredient list is read, set a count of 0 for each recipe.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Maintain a missing-ingredient count for every recipe, incremented only for ingredients not already available.","doneWhen":"This step is done when every recipe has a count that starts at zero and rises only for ingredients absent from supplies.","shouldFailWhen":"This step should fail if supplied ingredients are counted or if some recipe has no count.","roles":["recipe","missing count","available supplies"],"mustProve":["Every recipe has a missing-ingredient count.","The count rises only for ingredients that are not already supplies."],"mustNotAccept":["Counting ingredients that are already in supplies.","Leaving some recipe without a count."]},"commonMistakes":["Creating a count only once a recipe turns out to be missing something"],"hint":"A recipe with nothing missing still needs its 0, because that 0 is how it gets found later."},{"id":"populate-graph","title":"Record each missing ingredient","description":"For each ingredient that is not among the supplies, add one to the recipe's count and add the recipe to that ingredient's waiting list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"For each missing ingredient of a recipe, add the ingredient to recipe link and increment the recipe's count together.","doneWhen":"This step is done when every unavailable ingredient both raises the recipe's count and gains a link to that recipe.","shouldFailWhen":"This step should fail if only the map or only the count is updated, or if available ingredients are linked.","roles":["recipe","missing ingredient","unlock map","missing count"],"mustProve":["Each missing ingredient increments the waiting recipe's count.","Each missing ingredient gains a link to the recipe that needs it."],"mustNotAccept":["Adding links for ingredients already in supplies.","Updating only the map or only the count."]},"commonMistakes":["Counting or listing an ingredient that is already among the supplies","Raising the count without adding the recipe to the waiting list, or the reverse"],"hint":"Both updates belong to the same ingredient: the count says how many arrivals to wait for, and the list says which recipes to tell. Keeping the supplies in a set makes the shelf test a single lookup."},{"id":"initialize-queue","title":"Queue the recipes that are ready","description":"Put every recipe whose count is 0 into a queue.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Seed the FIFO queue with every recipe that has zero missing ingredients.","doneWhen":"This step is done when the queue holds exactly the recipes whose missing count is zero before processing starts.","shouldFailWhen":"This step should fail if the queue starts from supplies or omits a ready recipe.","roles":["ready recipe","queue","missing count"],"mustProve":["Every recipe with missing count zero is queued before processing.","The frontier is a FIFO queue."],"mustNotAccept":["Seeding the queue from supplies instead of makeable recipes.","Omitting a recipe whose count is already zero."]},"commonMistakes":["Queuing the supplies, which then come off the queue into the result list","Stopping at the first recipe found at 0 when several start there"],"hint":"These are the recipes whose ingredients are all among the supplies."},{"id":"record-recipes","title":"Make the recipe at the front","description":"While the queue holds a recipe, take the one at the front and add it to the result list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Run the queue loop and record each recipe in the answer as it is taken off the front.","doneWhen":"This step is done when the loop removes recipes in FIFO order and appends each one to the answer list.","shouldFailWhen":"This step should fail if the loop never records a made recipe or removes from the wrong end.","roles":["queue","current recipe","answer list"],"mustProve":["Each queued recipe is removed from the front.","Each made recipe is appended to the answer list."],"mustNotAccept":["Treating the queue as a stack.","Failing to append a made recipe to the answer."]},"commonMistakes":["Leaving the removed recipe out of the result list"],"hint":"Coming off the queue is the moment a recipe counts as made."},{"id":"update-neighbors","title":"Tell the recipes that were waiting","description":"For each recipe on the made recipe's waiting list, lower its count by one, and queue it if the count is now 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Treat each made recipe as a newly available ingredient, decrementing every dependent and queuing any that reach zero.","doneWhen":"This step is done when the dependent loop lowers each waiting recipe's count and queues any whose count reaches zero.","shouldFailWhen":"This step should fail if dependents are not decremented or a zero-count recipe is not queued.","roles":["current recipe","dependent recipe","missing count","queue"],"mustProve":["Every recipe waiting on the made one is decremented.","A dependent whose count reaches zero is queued."],"mustNotAccept":["Skipping the dependents of the made recipe.","Forgetting to queue a recipe once its count reaches zero."]},"commonMistakes":["Queuing a waiting recipe as soon as its count drops, before it reaches 0","Lowering the count but never queuing the recipe when it reaches 0"],"hint":"A finished recipe is an ingredient that has just arrived for every recipe waiting on it."},{"id":"return-recipes","title":"Return the recipes that were made","description":"Once the queue is empty, return the result list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topological_order_result","scope":"return-result","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Return exactly the recipes that reached zero missing ingredients through the unlock walk.","doneWhen":"This step is done when the recorded recipe list is returned after the queue drains.","shouldFailWhen":"This step should fail if blocked recipes are returned or the recorded list is discarded.","roles":["answer list","made recipes"],"mustProve":["The returned list is the recipes recorded by the walk."],"mustNotAccept":["Returning recipes that never reached zero missing ingredients.","Returning the original recipe list unchanged."]},"commonMistakes":["Returning the full recipe list, which includes recipes that stayed blocked"],"hint":"The result list already holds exactly the recipes that came off the queue."}],"slides":[{"id":"opener","kind":"info","title":"Find every recipe the kitchen can make","workspacePanel":"problem","body":["You are given a list of recipes, the ingredients each recipe needs, and the supplies already on the shelf.","A recipe can be made when everything it needs is either on the shelf or is another recipe that can be made. Return every recipe that can be made, in any order.","This kitchen has three recipes, taco, slaw and mayo, and four supplies."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"kitchen","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"}}}]}},{"id":"makeable-probe","kind":"case-probe","title":"Which of these recipes can be made?","workspacePanel":"visualizer","options":[{"id":"all-three","label":"All three: mayo, then slaw, then taco","rationale":"egg and oil are on the shelf, so mayo can be made. That gives slaw its mayo, and kale is on the shelf. taco, first on the list, is ready last, once it has slaw, mayo and beef.","isCorrect":true},{"id":"only-mayo","label":"Only mayo: slaw and taco need things that are not on the shelf","rationale":"A recipe that has been made counts as available. Once mayo is made, slaw has everything it needs.","isCorrect":false},{"id":"mayo-used-up","label":"mayo and slaw: the mayo went into the slaw, so taco has none","rationale":"Nothing is used up. Once mayo is made, every recipe that lists it can use it.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"kitchen","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"}}}]}},{"id":"brute-force","kind":"info","title":"Sweep the list until a sweep makes nothing","workspacePanel":"visualizer","body":["Working it out by hand was a loop. Go down the list and make every recipe whose ingredients are all available. That is one sweep. Then start again from the top, and stop when a whole sweep makes nothing new.","Count how many times taco gets checked."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-1-taco","title":"Sweep 1 checks taco","summary":"slaw and mayo have not been made, so taco has to wait.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":[]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"taco","sweep":1}},{"id":"sweep-1-slaw","title":"Sweep 1 checks slaw","summary":"slaw needs mayo, which has not been made either.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":[]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"slaw","sweep":1}},{"id":"sweep-1-mayo","title":"Sweep 1 makes mayo","summary":"egg and oil are both on the shelf. mayo goes into `result`, the list of recipes made so far.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":["mayo"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"mayo","sweep":1}},{"id":"sweep-2","title":"Sweep 2 makes slaw","summary":"taco is checked again and still lacks slaw. slaw now has mayo and kale, so it is made.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":["mayo","slaw"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"slaw","sweep":2}},{"id":"sweep-3","title":"Sweep 3 makes taco","summary":"taco is checked a third time. slaw, mayo and beef are all available now.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":["mayo","slaw","taco"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"taco","sweep":3}},{"id":"sweep-4","title":"Sweep 4 makes nothing","summary":"All three recipes are already in `result`, so the loop stops and returns it.","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":["mayo","slaw","taco"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"sweep":4}}]}},{"id":"sweep-cost","kind":"case-probe","title":"Picture 100 recipes chained like these, each listed before the one it needs. How many sweeps does it take?","workspacePanel":"visualizer","options":[{"id":"one-per-recipe","label":"About 100: each sweep makes one more recipe","rationale":"Only the last recipe in the list is ready at the start. Each sweep makes the next one up the list, so the first recipe is reached on sweep 100. Every sweep walks all 100 recipes, so that is about 100 × 100 visits to return 100 names.","isCorrect":true},{"id":"one-sweep","label":"1: a single sweep visits every recipe","rationale":"It visits them in list order. The first 99 are checked before the recipe they need has been made.","isCorrect":false},{"id":"halving","label":"About 7: each sweep settles half of what is left","rationale":"Nothing here halves. In this order every sweep but the last makes exactly one recipe.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-sweeps","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]},{"name":"result","values":["mayo","slaw","taco"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"sweep":4}}]}},{"id":"count-remaining","kind":"case-probe","title":"The sweeps read taco's ingredient list again every time. What could be stored for taco so that its list is read only once?","workspacePanel":"visualizer","options":[{"id":"missing-count","label":"How many of its ingredients are still missing","rationale":"It drops by one when slaw is made and by one when mayo is made. When it reaches 0, taco can be made without reading the list again. This number is the recipe's missing count, and every recipe gets one.","isCorrect":true},{"id":"ready-flag","label":"Whether it can be made yet, yes or no","rationale":"The answer was no before mayo was made and it is still no afterward. A yes or no cannot record that mayo has arrived while slaw is still missing.","isCorrect":false},{"id":"last-sweep","label":"Which sweep last checked it","rationale":"That records when taco was looked at and says nothing about slaw or mayo. The next sweep would have to read the list again.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"taco-list","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"taco"}}]}},{"id":"count-start","kind":"case-probe","title":"What should taco's missing count start at?","workspacePanel":"visualizer","options":[{"id":"two","label":"2, for slaw and mayo","rationale":"beef is already on the shelf, so taco is waiting only for slaw and mayo. The count covers only ingredients that are not on the shelf.","isCorrect":true},{"id":"three","label":"3, one for each ingredient it lists","rationale":"beef is on the shelf and nothing will ever make it. With beef counted, taco would stop at 1 after slaw and mayo were made and never reach 0.","isCorrect":false},{"id":"zero","label":"0, since slaw and mayo can both be made","rationale":"slaw and mayo can be made, but neither has been made yet. Until they are, taco is missing both.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"taco-list","state":{"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":["slaw","mayo","beef"],"slaw":["mayo","kale"],"mayo":["egg","oil"]},"labels":{"seen":"ingredients"},"seenHighlight":"taco"}}]}},{"id":"reverse-links-probe","kind":"case-probe","title":"mayo has just been made. How do you find the counts to lower?","workspacePanel":"visualizer","options":[{"id":"ingredient-to-waiters","label":"Keep, for each ingredient, the recipes waiting on it","rationale":"Looking up mayo gives slaw and taco directly. No other recipe is touched.","isCorrect":true},{"id":"search-lists","label":"Search every recipe's ingredient list for mayo","rationale":"That is the sweep again. Every list gets read to find the two that mention mayo.","isCorrect":false},{"id":"lower-all","label":"Lower every recipe's count by one","rationale":"A recipe that never listed mayo would have its count lowered for an ingredient it was not waiting on. It could reach 0 with an ingredient still missing.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"mayo-made","state":{"arrays":[{"name":"result","values":["mayo"]}],"seen":{"taco":2,"slaw":1,"mayo":0},"labels":{"seen":"missing"},"seenHighlight":"mayo"}}]}},{"id":"build-it-bridge","kind":"info","title":"One pass over the lists sets up the counts and the waiting lists","workspacePanel":"visualizer","body":["Read each recipe's list once. An ingredient on the shelf is skipped. Any other ingredient adds one to the recipe's count and puts the recipe on that ingredient's waiting list, drawn here as an arrow."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"build-taco-slaw","title":"taco lists slaw","summary":"slaw is not on the shelf. taco's count becomes 1 and slaw gets an arrow to taco.","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"]],"current":"taco","highlighted":["slaw"],"activeEdges":[["slaw","taco"]]},"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":1},"labels":{"seen":"missing"}}},{"id":"build-taco-mayo","title":"taco lists mayo, then beef","summary":"mayo is not on the shelf either, so the count becomes 2 and mayo points to taco. beef is on the shelf and is skipped.","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"]],"current":"taco","highlighted":["mayo"],"activeEdges":[["mayo","taco"]]},"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":2},"labels":{"seen":"missing"}}},{"id":"build-slaw","title":"slaw lists mayo, then kale","summary":"slaw's count becomes 1 and mayo now points to slaw as well. kale is on the shelf.","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"current":"slaw","highlighted":["mayo"],"activeEdges":[["mayo","slaw"]]},"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":2,"slaw":1},"labels":{"seen":"missing"}}},{"id":"build-mayo","title":"mayo lists egg and oil","summary":"Both are on the shelf, so mayo's count stays at 0 and no arrow is added.","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"current":"mayo"},"arrays":[{"name":"supplies","values":["egg","oil","kale","beef"]}],"seen":{"taco":2,"slaw":1,"mayo":0},"labels":{"seen":"missing"}}}]}},{"id":"dry-run-setup","kind":"case-probe","title":"Recipes that are ready to be made wait in a queue. Which ones start in it?","workspacePanel":"visualizer","options":[{"id":"zero-count","label":"Every recipe whose count is 0, which here is mayo","rationale":"A count of 0 means nothing is missing, so mayo can be made before anything else happens. Each recipe taken off the front of the queue is made and added to `result`.","isCorrect":true},{"id":"supplies","label":"The supplies: egg, oil, kale and beef","rationale":"No waiting list starts from a supply, so taking one off the queue would lower no counts. egg, oil, kale and beef are not recipes either, and only recipes are returned.","isCorrect":false},{"id":"first-listed","label":"The first recipe in the list, taco","rationale":"taco's count is 2. It cannot be made until slaw and mayo are.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"counts-and-arrows","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]]},"seen":{"taco":2,"slaw":1,"mayo":0},"labels":{"seen":"missing"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Run the queue on this kitchen","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"queue":["mayo"]},"seen":{"taco":2,"slaw":1,"mayo":0},"labels":{"seen":"missing"}}},{"id":"make-mayo","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"visited":["mayo"],"queue":["slaw"]},"seen":{"taco":1,"slaw":0,"mayo":0},"labels":{"seen":"missing"}}},{"id":"make-slaw","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"visited":["mayo","slaw"],"queue":["taco"]},"seen":{"taco":0,"slaw":0,"mayo":0},"labels":{"seen":"missing"}}},{"id":"make-taco","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"visited":["mayo","slaw","taco"]},"seen":{"taco":0,"slaw":0,"mayo":0},"labels":{"seen":"missing"}}}]},"beats":[{"id":"make-mayo","title":"mayo comes off the queue and is made. What happens to slaw and taco?","options":[{"id":"slaw-ready-taco-waits","label":"slaw drops to 0 and joins the queue; taco drops to 1","rationale":"Both are on mayo's waiting list, so both counts drop by one. Only slaw reaches 0.","isCorrect":true},{"id":"both-ready","label":"Both drop to 0 and join the queue","rationale":"taco started at 2. One arrival brings it to 1, and it is still waiting for slaw.","isCorrect":false},{"id":"only-slaw","label":"Only slaw changes; taco waits for slaw first","rationale":"mayo points to taco as well. Every recipe on mayo's waiting list loses one from its count.","isCorrect":false}]},{"id":"make-slaw","title":"slaw comes off the queue next. What does making it do to taco?","options":[{"id":"taco-ready","label":"taco drops from 1 to 0 and joins the queue","rationale":"slaw was the last ingredient taco was waiting for.","isCorrect":true},{"id":"next-sweep","label":"taco stays at 1 until the list is swept again","rationale":"Nothing sweeps the list anymore. slaw's arrow leads straight to taco, and the count drops as soon as slaw is made.","isCorrect":false},{"id":"already-queued","label":"Nothing: taco joined the queue when mayo was made","rationale":"taco was still at 1 after mayo, so it was not queued then. A recipe joins the queue once, when its count reaches 0.","isCorrect":false}]},{"id":"make-taco","title":"taco comes off the queue and no arrow leaves it. What happens next?","options":[{"id":"loop-ends","label":"The queue is empty, so the loop ends","rationale":"No count changed, so nothing new was queued. `result` holds all three recipes, each made once.","isCorrect":true},{"id":"final-sweep","label":"One last sweep of the list checks for anything missed","rationale":"A recipe is queued the moment its count reaches 0, so no recipe can be ready without having been in the queue.","isCorrect":false},{"id":"requeue","label":"taco goes back into the queue, since its count is 0","rationale":"Reaching 0 is what queued taco in the first place. Nothing lowers the count again, so it is never queued twice.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"All three recipes got made in this kitchen. Next, two small changes to it.","workspacePanel":"visualizer","body":["First, beef comes off the shelf. Then beef goes back, and mayo's recipe starts asking for taco. Does the same function still return the right recipes?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-made","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"visited":["mayo","slaw","taco"]},"arrays":[{"name":"queue","values":[]},{"name":"result","values":["mayo","slaw","taco"]}],"seen":{"taco":0,"slaw":0,"mayo":0},"labels":{"seen":"missing"}}}]}},{"id":"missing-base-edge","kind":"case-probe","title":"First, with beef off the shelf, what does the function return?","workspacePanel":"visualizer","options":[{"id":"made-only","label":"mayo and slaw, but not taco","rationale":"taco started at 3 this time, for slaw, mayo and beef. Making mayo and slaw brought it to 1, and nothing will ever make beef. taco is never queued, so returning `result` needs no check for blocked recipes.","isCorrect":true},{"id":"all-recipes","label":"All three recipes, once the queue empties","rationale":"The loop finishing only means the queue is empty. taco never reached 0, so it was never made.","isCorrect":false},{"id":"nothing","label":"Nothing, because one recipe could not be made","rationale":"mayo and slaw never needed beef. One blocked recipe does not undo the ones that were made.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"no-beef-start","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"},{"id":"beef","label":"beef"}],"edges":[["slaw","taco"],["mayo","taco"],["beef","taco"],["mayo","slaw"]],"queue":["mayo"]},"seen":{"taco":3,"slaw":1,"mayo":0},"labels":{"seen":"missing"}}}]}},{"id":"cycle-edge","kind":"case-probe","title":"Now beef is back, and mayo's recipe also asks for taco. What does the kitchen make?","workspacePanel":"visualizer","options":[{"id":"nothing","label":"Nothing: no recipe starts with a count of 0","rationale":"mayo waits on taco, taco waits on slaw and mayo, and slaw waits on mayo. The queue starts empty, so the loop never runs. Like taco without beef, each recipe in the circle stays above 0, so no cycle check is needed.","isCorrect":true},{"id":"mayo-first","label":"mayo, because egg and oil are on the shelf","rationale":"mayo's list now has taco on it too. Its count starts at 1 and nothing can lower it.","isCorrect":false},{"id":"never-finishes","label":"It never finishes: the three keep waiting on each other","rationale":"The loop runs only while the queue holds a recipe. Here the queue starts empty, so the function returns right away.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cycle-counts","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"],["taco","mayo"]]},"seen":{"taco":2,"slaw":1,"mayo":1},"labels":{"seen":"missing"}}}]}},{"id":"ready-to-code","kind":"info","title":"A count for each recipe, a waiting list for each missing ingredient","workspacePanel":"visualizer","body":["In one pass over the ingredient lists, the function gives every recipe a missing count and every missing ingredient a waiting list. Ingredients on the shelf are skipped.","Every recipe whose count is 0 goes into a queue. While the queue holds a recipe, the one at the front is made and added to the result, and every recipe waiting on it loses one from its count. A recipe that reaches 0 joins the queue.","When the queue is empty, the function returns the recipes it made."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":"taco","label":"taco"},{"id":"slaw","label":"slaw"},{"id":"mayo","label":"mayo"}],"edges":[["slaw","taco"],["mayo","taco"],["mayo","slaw"]],"queue":["mayo"]},"seen":{"taco":2,"slaw":1,"mayo":0},"labels":{"seen":"missing"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Find every recipe that can be made","workspacePanel":"code","checkpoints":[{"id":"build-graph","title":"Start the waiting lists","description":"Create an empty map from an ingredient to the recipes that are waiting on it.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_adjacency","scope":"build-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Create the adjacency map that points each blocked ingredient at the recipes depending on it.","doneWhen":"This step is done when an empty adjacency container exists to hold ingredient to dependent-recipe links before the scan runs.","shouldFailWhen":"This step should fail if links run from recipe to ingredient instead of ingredient to recipe.","roles":["unlock map","available supplies","blocked ingredient"],"mustProve":["An adjacency container is created to map an ingredient to the recipes waiting on it."],"mustNotAccept":["Storing edges only from a recipe to its ingredients.","Skipping the ingredient to dependent-recipe direction."]},"commonMistakes":["Keying the map by recipe, which only answers what that recipe needs"],"hint":"The lookup starts from the thing that was just made, so the ingredient is the key."},{"id":"calculate-indegree","title":"Give every recipe a missing count","description":"Before any ingredient list is read, set a count of 0 for each recipe.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_course_indegree","scope":"calculate-indegree","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Maintain a missing-ingredient count for every recipe, incremented only for ingredients not already available.","doneWhen":"This step is done when every recipe has a count that starts at zero and rises only for ingredients absent from supplies.","shouldFailWhen":"This step should fail if supplied ingredients are counted or if some recipe has no count.","roles":["recipe","missing count","available supplies"],"mustProve":["Every recipe has a missing-ingredient count.","The count rises only for ingredients that are not already supplies."],"mustNotAccept":["Counting ingredients that are already in supplies.","Leaving some recipe without a count."]},"commonMistakes":["Creating a count only once a recipe turns out to be missing something"],"hint":"A recipe with nothing missing still needs its 0, because that 0 is how it gets found later."},{"id":"populate-graph","title":"Record each missing ingredient","description":"For each ingredient that is not among the supplies, add one to the recipe's count and add the recipe to that ingredient's waiting list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"populates_graph_and_indegree","scope":"populate-graph","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"For each missing ingredient of a recipe, add the ingredient to recipe link and increment the recipe's count together.","doneWhen":"This step is done when every unavailable ingredient both raises the recipe's count and gains a link to that recipe.","shouldFailWhen":"This step should fail if only the map or only the count is updated, or if available ingredients are linked.","roles":["recipe","missing ingredient","unlock map","missing count"],"mustProve":["Each missing ingredient increments the waiting recipe's count.","Each missing ingredient gains a link to the recipe that needs it."],"mustNotAccept":["Adding links for ingredients already in supplies.","Updating only the map or only the count."]},"commonMistakes":["Counting or listing an ingredient that is already among the supplies","Raising the count without adding the recipe to the waiting list, or the reverse"],"hint":"Both updates belong to the same ingredient: the count says how many arrivals to wait for, and the list says which recipes to tell. Keeping the supplies in a set makes the shelf test a single lookup."},{"id":"initialize-queue","title":"Queue the recipes that are ready","description":"Put every recipe whose count is 0 into a queue.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"seeds_zero_indegree_frontier","scope":"initialize-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Seed the FIFO queue with every recipe that has zero missing ingredients.","doneWhen":"This step is done when the queue holds exactly the recipes whose missing count is zero before processing starts.","shouldFailWhen":"This step should fail if the queue starts from supplies or omits a ready recipe.","roles":["ready recipe","queue","missing count"],"mustProve":["Every recipe with missing count zero is queued before processing.","The frontier is a FIFO queue."],"mustNotAccept":["Seeding the queue from supplies instead of makeable recipes.","Omitting a recipe whose count is already zero."]},"commonMistakes":["Queuing the supplies, which then come off the queue into the result list","Stopping at the first recipe found at 0 when several start there"],"hint":"These are the recipes whose ingredients are all among the supplies."},{"id":"record-recipes","title":"Make the recipe at the front","description":"While the queue holds a recipe, take the one at the front and add it to the result list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"records_topological_order","scope":"process-queue","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Run the queue loop and record each recipe in the answer as it is taken off the front.","doneWhen":"This step is done when the loop removes recipes in FIFO order and appends each one to the answer list.","shouldFailWhen":"This step should fail if the loop never records a made recipe or removes from the wrong end.","roles":["queue","current recipe","answer list"],"mustProve":["Each queued recipe is removed from the front.","Each made recipe is appended to the answer list."],"mustNotAccept":["Treating the queue as a stack.","Failing to append a made recipe to the answer."]},"commonMistakes":["Leaving the removed recipe out of the result list"],"hint":"Coming off the queue is the moment a recipe counts as made."},{"id":"update-neighbors","title":"Tell the recipes that were waiting","description":"For each recipe on the made recipe's waiting list, lower its count by one, and queue it if the count is now 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"updates_topology_neighbors","scope":"update-neighbors","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Treat each made recipe as a newly available ingredient, decrementing every dependent and queuing any that reach zero.","doneWhen":"This step is done when the dependent loop lowers each waiting recipe's count and queues any whose count reaches zero.","shouldFailWhen":"This step should fail if dependents are not decremented or a zero-count recipe is not queued.","roles":["current recipe","dependent recipe","missing count","queue"],"mustProve":["Every recipe waiting on the made one is decremented.","A dependent whose count reaches zero is queued."],"mustNotAccept":["Skipping the dependents of the made recipe.","Forgetting to queue a recipe once its count reaches zero."]},"commonMistakes":["Queuing a waiting recipe as soon as its count drops, before it reaches 0","Lowering the count but never queuing the recipe when it reaches 0"],"hint":"A finished recipe is an ingredient that has just arrived for every recipe waiting on it."},{"id":"return-recipes","title":"Return the recipes that were made","description":"Once the queue is empty, return the result list.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_topological_order_result","scope":"return-result","readMode":"graph-value-query-v1"}]},"semanticSpec":{"intent":"Return exactly the recipes that reached zero missing ingredients through the unlock walk.","doneWhen":"This step is done when the recorded recipe list is returned after the queue drains.","shouldFailWhen":"This step should fail if blocked recipes are returned or the recorded list is discarded.","roles":["answer list","made recipes"],"mustProve":["The returned list is the recipes recorded by the walk."],"mustNotAccept":["Returning recipes that never reached zero missing ingredients.","Returning the original recipe list unchanged."]},"commonMistakes":["Returning the full recipe list, which includes recipes that stayed blocked"],"hint":"The result list already holds exactly the recipes that came off the queue."}]},{"id":"complete","kind":"complete","title":"A recipe can be made once its count reaches 0","workspacePanel":"code","takeaways":[{"title":"Count only what is not on the shelf","body":"A recipe's count starts at the number of its ingredients that are not among the supplies. No supply has a waiting list, so nothing would ever lower a count for one, and counting it would hold the recipe above 0 for good."},{"title":"A finished recipe reaches only the recipes waiting on it","body":"Each missing ingredient has a list of the recipes waiting on it. Making a recipe lowers exactly those counts, and a recipe joins the queue once, when its count reaches 0."},{"title":"Blocked recipes need no special case","body":"A recipe that needs something nobody can make, or that sits in a circle of recipes waiting on each other, never reaches 0. It is never queued, so it never enters the result."},{"title":"O(r + e + s) time and space","body":"With the supplies in a set, every ingredient entry is read once and every waiting link is followed at most once. For r recipes, e ingredient entries and s supplies, that is O(r + e + s) time, and the counts, the lists and the set take O(r + e + s) space. The repeated sweeps can take r sweeps that each visit every recipe and reread its list, O(r × (r + e))."}]}],"slidesOrigin":"authored"}}
