← Questions

Count recipes a pantry can cover

0
MicrosoftCoding

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^4
  • 0 <= 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 repeated str.count is 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

hash map · counting · strings

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding