Find All Possible Recipes from Given Supplies

Which recipes are makeable from initial supplies? Topological sort over the ingredient DAG.

Medium
Time O(V + E) Space O(V + E)
LeetCode
4 min read
topological-sort graph

Problem#

Each recipe needs ingredients. Some ingredients are initial supplies; others may be other recipes. Return all recipes that can be produced.

Examples#

  • recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]["bread"]

Constraints#

  • 1 <= recipes.length <= 100.

Approach#

Build an edge from each ingredient to each recipe that needs it; recipe’s in-degree = ingredient count. Initial supplies have in-degree 0; enqueue them. BFS reduces neighbors’ in-degrees; a recipe is producible when its in-degree hits 0.

Solution#

Find Possible Recipes
class Solution {
public:
vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) {
unordered_map<string, vector<string>> adj;
unordered_map<string, int> indeg;
unordered_set<string> recipeSet(recipes.begin(), recipes.end());
for (int i = 0; i < (int)recipes.size(); ++i) {
indeg[recipes[i]] = ingredients[i].size();
for (auto& ing : ingredients[i]) adj[ing].push_back(recipes[i]);
}
queue<string> q;
for (auto& s : supplies) q.push(s);
vector<string> out;
while (!q.empty()) {
string u = q.front(); q.pop();
for (auto& v : adj[u]) {
if (--indeg[v] == 0) {
out.push_back(v);
q.push(v);
}
}
}
return out;
}
};

Editorial#

The clever bit: supplies aren’t in indeg (in-degree 0 by absence), but neighbors are decremented anyway because we processed them through the queue. Only recipes get added to the output.

Complexity#

  • Time: O(V + E).
  • Space: O(V + E).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.