Find All Possible Recipes solution explained

Find All Possible Recipes is a topological sort in disguise. Treat every ingredient and recipe as a node, give each recipe a counter of ingredients still missing, start a queue with the supplies, and each time an item becomes available, lower the counter of every recipe that needs it; a recipe whose counter reaches zero is made and joins the queue. That runs in time linear in the total size of the input.

By Published 8 min read

The problem in plain words

You have three inputs. A list of recipe names. A matching list where entry i holds the ingredients recipe i needs. And a list of supplies you already have in unlimited quantity. A recipe can be made when every one of its ingredients is either a supply or a recipe you can make. Some ingredients are neither, so recipes that need them are out of reach. Return all recipes that can be made, in any order.

Kitchen examples written for this page
Recipes and their ingredientsSuppliesCan makeWhy
toast: bread / jam toast: toast, jambread, jamtoast, jam toastToast is made from a supply, and then it feeds jam toast.
soup: water, leekwaternothingLeek is not a supply and not a recipe.
dough: flour, starter / starter: dough, flourflournothingEach recipe waits on the other, so neither ever starts.
pie: crust, apple / crust: flour, butterapple, flournothingButter is missing, so crust fails, so pie fails.
salad: greens / dressing: oil, salt / bowl: salad, dressinggreens, oil, saltsalad, dressing, bowlTwo independent recipes unlock a third.
Kitchen examples written for this page. Scroll sideways on a small screen.

Good questions to ask: are recipe names and supply names all different from each other? Can a recipe list the same ingredient twice? Does the output need a particular order? The usual answers are that names are distinct, duplicates do not appear, and any order is fine, but each answer affects one line of the code.

Why interviewers like it

Course scheduling problems use integer node ids and say plainly that you are dealing with prerequisites. This one hides the same structure behind strings and a story, and adds a third category of item that is simply unavailable. It tests whether you recognize a dependency graph without being told, whether you can build adjacency from string keys cleanly, and whether you can explain why cyclic recipes are excluded without writing separate cycle detection.

Slow approach: sweep until nothing changes

Keep a set of everything available, starting with the supplies. Loop over all recipes not yet made. If every ingredient is in the set, add the recipe to the set and to the answer. Repeat the full sweep until one pass makes nothing new. Each sweep costs the total number of ingredient entries, and in the worst case each sweep makes only one new recipe, so with R recipes the time is O(R · total ingredients). It is correct and quick to write, and it reads like the problem statement.

def makeable_slow(recipes, needs, supplies):
    have = set(supplies)
    made = []
    progress = True
    while progress:
        progress = False
        for name, parts in zip(recipes, needs):
            if name not in have and all(p in have for p in parts):
                have.add(name)
                made.append(name)
                progress = True
    return made
Slow version: repeated sweeps to a fixed point.

If the recipes happen to be listed so that each one depends on the recipe after it, every sweep unlocks just one, and the cost becomes quadratic. That ordering is the case to mention when you explain why you want something better.

Main approach: Kahn's algorithm on names

Build a reverse index from each ingredient to the recipes that use it. Give every recipe a counter equal to the number of ingredients it lists. Put every supply in a queue. Pop an item, and for each recipe that uses it, lower that recipe's counter. When a counter reaches zero, every ingredient of that recipe has become available, so record the recipe and push it onto the queue, because it may be an ingredient of something else.

Missing ingredients are never pushed, so recipes that need them keep a counter above zero. Recipes in a dependency loop each wait for the other to be pushed first, so their counters also stay above zero. That is why no explicit cycle check is needed.

from collections import defaultdict, deque

def makeable(recipes, needs, supplies):
    missing = {name: len(parts) for name, parts in zip(recipes, needs)}
    used_by = defaultdict(list)
    for name, parts in zip(recipes, needs):
        for part in parts:
            used_by[part].append(name)
    queue = deque(set(supplies))
    made = []
    while queue:
        item = queue.popleft()
        for name in used_by.get(item, []):
            missing[name] -= 1
            if missing[name] == 0:
                made.append(name)
                queue.append(name)
    return made
Python: in-degree counting with a queue, linear in the input size.
function makeable(recipes, needs, supplies) {
  const missing = new Map();
  const usedBy = new Map();
  recipes.forEach((name, i) => {
    missing.set(name, needs[i].length);
    for (const part of needs[i]) {
      if (!usedBy.has(part)) usedBy.set(part, []);
      usedBy.get(part).push(name);
    }
  });
  const queue = [...new Set(supplies)];
  const made = [];
  for (let head = 0; head < queue.length; head++) {
    for (const name of usedBy.get(queue[head]) || []) {
      const left = missing.get(name) - 1;
      missing.set(name, left);
      if (left === 0) {
        made.push(name);
        queue.push(name);
      }
    }
  }
  return made;
}
JavaScript: the same idea with Map for the reverse index and counters.

Two small choices protect you. Removing duplicate supplies with a set prevents one supply from lowering a counter twice. And if a recipe did list the same ingredient twice, the reverse index holds it twice and the counter starts at two, so the arithmetic still balances.

The DFS alternative

You can also ask, for each recipe, whether it can be made, using DFS with memoization and three states: unknown, in progress and decided. Reaching an in-progress recipe means a loop, which answers no. It works and some candidates find it more natural, but recursion depth and the extra state make it easier to get wrong under pressure than the queue.

Tracing the salad example

  1. Set upCounters: salad 1, dressing 2, bowl 2. The queue holds greens, oil and salt.
  2. Pop greensSalad drops to 0, so salad is made and pushed.
  3. Pop oil and saltDressing drops to 1, then 0. Dressing is made and pushed.
  4. Pop salad, then dressingBowl drops to 1, then 0, and is made. The queue empties. The answer is salad, dressing and bowl.

Complexity

Cost in terms of R recipes, E total ingredient entries and S supplies
ApproachTimeExtra space
Sweep until stableO(R · E)O(R + S)
Kahn's algorithmO(R + E + S)O(R + E + S)
DFS with memo and statesO(R + E + S)O(R + E) plus recursion depth
Cost in terms of R recipes, E total ingredient entries and S supplies. Scroll sideways on a small screen.

Hashing strings adds a cost proportional to name length. Interviewers rarely ask about it, but it is the honest qualifier if someone pushes on the bound.

Edge cases to test

  • A recipe with an ingredient that is neither a supply nor a recipe.
  • Two recipes that need each other, and a third recipe that needs one of them. All three must be excluded.
  • A recipe that lists itself as an ingredient.
  • A chain where recipe A needs B, B needs C, and C needs only supplies. All three are made, in reverse order.
  • Duplicate names in the supplies list.
  • No supplies at all: nothing can be made unless a recipe has an empty ingredient list, which most versions forbid.

Common mistakes

  • Marking a recipe as made the moment one ingredient arrives, instead of waiting for its counter to reach zero.
  • Forgetting to push a newly made recipe onto the queue, so recipes that depend on it are never unlocked.
  • Running DFS without an in-progress state and recursing forever on a cyclic pair.
  • Indexing used_by[item] on a plain dict in Python for an item no recipe uses, which raises a KeyError.
  • Sorting the output when the problem accepts any order, which adds O(R log R) for nothing.

Saying it out loud

Fictional example

A clear two-minute explanation
Candidate
This is a dependency graph. Edges go from an ingredient to the recipes that use it, and supplies are the starting nodes.
Candidate
I will keep a count of missing ingredients for each recipe. Popping an available item lowers the count for the recipes that use it, and any recipe that hits zero is made and becomes available itself.
Candidate
Missing ingredients and loops both leave counts above zero, so they drop out without a separate check. Time is linear in recipes plus ingredient entries plus supplies.

Neighbors in this batch

The same peel-from-the-sources idea appears in Longest Cycle in a Graph, where removing nodes with no incoming arrows leaves only the cycles. Loud and Rich uses a topological order to push a best-so-far answer down the graph, a natural next step. Course Schedule IV asks a reachability question on the same kind of dependency graph. More dependency-graph questions sit on the algorithm interview questions page.

Where Natively fits

As you practice dependency problems, Natively can read the statement from a screenshot and sketch a solution path, which you can check against your own plan after you have one. Because it transcribes a mock session on your computer, you can review whether you named Kahn's algorithm and explained why cycles drop out. Background on AI help for coding interviews.

Questions people ask

What algorithm solves Find All Possible Recipes?

Kahn's algorithm. Give each recipe a count of missing ingredients, start a queue with the supplies, and lower counts as items become available. A recipe whose count reaches zero is made and joins the queue.

How are recipes that depend on each other handled?

They are excluded automatically. In a loop, each recipe waits for the other to become available first, so neither count ever reaches zero and neither is output.

What is the time complexity of the topological sort solution?

It is linear in the number of recipes plus the total number of ingredient entries plus the number of supplies, ignoring the cost of hashing the names.

Can I solve it with DFS instead?

Yes, with memoization and three states per recipe: unknown, in progress and decided. Reaching an in-progress recipe signals a loop. The queue version is usually simpler to get right.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP