AI for meal planning and recipes in AI for Everyone - Time & Space Complexity
When AI helps plan meals and suggest recipes, it processes many options to find the best fit. Understanding how the time it takes grows with more recipes or ingredients is important.
We want to know how the AI's work increases as the number of recipes or ingredients grows.
Analyze the time complexity of the following code snippet.
function suggestRecipes(ingredients, recipes) {
let matches = []
for (let recipe of recipes) {
let matchCount = 0
for (let ingredient of ingredients) {
if (recipe.includes(ingredient)) {
matchCount++
}
}
if (matchCount > 0) {
matches.push(recipe)
}
}
return matches
}
This code checks each recipe to see how many ingredients match the user's available ingredients, then collects recipes with at least one match.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops where for each recipe, it checks all ingredients.
- How many times: The inner loop runs once for every ingredient inside the outer loop that runs once for every recipe.
As the number of recipes and ingredients grows, the total checks increase by multiplying these two numbers.
| Input Size (recipes x ingredients) | Approx. Operations |
|---|---|
| 10 x 5 | 50 checks |
| 100 x 20 | 2,000 checks |
| 1000 x 50 | 50,000 checks |
Pattern observation: Doubling recipes or ingredients roughly doubles the work, so work grows with the product of both.
Time Complexity: O(r * i * m)
This means the time to suggest recipes grows in proportion to the number of recipes times the number of ingredients times the average length of each recipe string.
[X] Wrong: "The time only depends on the number of recipes, not ingredients."
[OK] Correct: Each recipe is checked against every ingredient, so both counts affect the total work.
Understanding how nested checks affect performance helps you explain AI system efficiency clearly. This skill shows you can think about how AI scales with more data.
"What if the AI used a fast lookup to check ingredients instead of looping through all? How would the time complexity change?"