Count recipes a pantry can cover
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests hash map, counting and strings.
You keep a pantry of ingredients, written as a string pantry. Each character is one unit of an ingredient, so "aab" holds two units of a and one unit of b.
You also have a list of strings recipes. Each recipe lists the units it needs in the same way: every character is one unit, and a character that appears twice needs two units.
Implement:
def count_makeable(recipes: list[str], pantry: str) -> int: ...
Return how many recipes the pantry can supply. A recipe can be made when, for every character, the pantry has at least as many units as the recipe needs. Check each recipe on its own against the full pantry: making one recipe does not use up units for the others.
Constraints
0 <= len(recipes) <= 10^40 <= len(pantry), len(recipes[i]) <= 10^4- Characters are case-sensitive. An empty recipe needs nothing and can always be made.
Example 1
recipes = ["bread", "dab", "zz"]
pantry = "abbreadd"
output = 2
"bread" and "dab" are both covered. "zz" needs two z units and the pantry has none.
Example 2
recipes = ["aa", "a", ""]
pantry = "a"
output = 2
"aa" needs two units of a but only one is available. "a" and the empty recipe can both be made.
Clarifying questions
- Is the check independent per recipe, so units are never used up?
- Are characters case-sensitive, with any character allowed, not only letters?
- Is the empty recipe counted as makeable?
- Will the same pantry be checked against many recipe lists?
What a strong answer covers
- Counts the pantry once into a dictionary (or a fixed array for ASCII).
- For each recipe, counts its characters and checks every count against the pantry, stopping at the first shortfall.
-
O(len(pantry) + total recipe length)time; notes that comparing each recipe by sorting or repeatedstr.countis slower. - Tests both examples, the empty pantry, and a recipe longer than the pantry.
Follow-ups
- Recipes consume the pantry: maximise the number of recipes made.
- Return how many copies of each recipe the pantry can supply.
- Many pantries and many recipes: precompute to answer fast.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
