Dsa
Recursion
Easy
The Alchemist's Component Count
An alchemist needs to know how many units of a 'Base' element are required to create a 'Target' compound. You are given a list of recipes where each compound is made of several ingredients (which could be other compounds or base elements). If an ingredient is not defined by a recipe, it is considered a base element. Calculate the total count of the specified Base element needed for one unit of the Target.
Input Format:
1. The name of the Target compound.
2. The name of the Base element to count.
3. An integer N, the number of recipes.
4. N lines, each in the format: 'Compound: Qty1 Ingredient1, Qty2 Ingredient2...'
Output Format:
A single integer representing the total amount of the Base element required.
Example:
Input:
Gold
Lead
2
Gold: 2 Mercury, 1 Sulfur
Mercury: 3 Lead, 1 Tin
Output:
6
(Explanation: 1 Gold needs 2 Mercury. 1 Mercury needs 3 Lead. Total Lead = 2 * 3 = 6.)
Key concepts
recursiontree traversaldictionary mapping
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now