FastPrepCan Inventory Satisfy a Nested Recipe?

Can Inventory Satisfy a Nested Recipe?

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
Learn

Problem statement

There are n item types. For item i, ingredients[i][j] is an ingredient item and quantities[i][j] is how many units of it are required to make one unit of item i.

An item with an empty ingredient list is a raw material. inventory[i] gives the available units of each raw material; inventory entries for composite items are zero. Recipe dependencies form a directed acyclic graph.

Return whether the inventory contains enough raw materials to make amount units of target.

Function

canMakeRecipe(ingredients: int[][], quantities: int[][], inventory: int[], target: int, amount: int) → boolean

Examples

Example 1

ingredients = [[],[],[0,1]]quantities = [[],[],[2,3]]inventory = [4,6,0]target = 2amount = 2return = true

Two target items require four units of raw item 0 and six units of raw item 1, exactly matching inventory.

Example 2

ingredients = [[],[0],[1]]quantities = [[],[3],[2]]inventory = [5,0,0]target = 2amount = 1return = false

The nested recipe expands to six units of raw item 0, but only five are available.

Example 3

ingredients = [[],[],[0],[1,2]]quantities = [[],[],[2],[1,3]]inventory = [6,1,0,0]target = 3amount = 1return = true

The target needs one unit of raw item 1 and three copies of item 2, which expand to six units of raw item 0.

Constraints

  • 1 <= n <= 1000.
  • ingredients.length = quantities.length = inventory.length = n.
  • ingredients[i].length = quantities[i].length.
  • Every ingredient index is valid, every quantity and amount is positive, and recipe dependencies are acyclic.
  • Only raw items have nonzero inventory.
  • Expanding the requested recipe visits at most 200000 recipe nodes, counting repeated dependency paths.
  • Every fully expanded raw-material requirement fits in a signed 64-bit integer.

More Google problems

See Google hiring insights
public boolean canMakeRecipe(int[][] ingredients, int[][] quantities, int[] inventory, int target, int amount) {
    // Write your code here.
}
ingredients[[],[],[0,1]]
quantities[[],[],[2,3]]
inventory[4,6,0]
target2
amount2
expectedtrue
Checking account…