Skip to main content
Back to problems
#2115
Medium Algorithms

Find all possible recipes from given supplies

Array Hash Table String Graph Theory Topological Sort
56.8% acceptance
Feb 25, 2026
2660
142
You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. A recipe can also be an ingredient for other recipes, i.e., ingredients[i] may contain a string that is in recipes. You are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_all_recipes(
    recipes: Vec<String>,
    ingredients: Vec<Vec<String>>,
    supplies: Vec<String>,
  ) -> Vec<String> {
    use std::collections::HashSet;
    let mut available: HashSet<String> = supplies.into_iter().collect();
    let mut pending: Vec<bool> = vec![true; recipes.len()];
    let mut result = Vec::new();
    let mut changed = true;

    while changed {
      changed = false;
      for i in 0..recipes.len() {
        if pending[i] && ingredients[i].iter().all(|ing| available.contains(ing)) {
          result.push(recipes[i].clone());
          available.insert(recipes[i].clone());
          pending[i] = false;
          changed = true;
        }
      }
    }
    result
  }
}