TikTok VO Interview Question: Count Elements in a Chemical Molecular Formula

18 Views
No Comments

Count elements in a chemical molecular formula.

Examples:

H2O
{"H": 2, "O": 1}

H2(CO2)2
{"H": 2, "C": 2, "O": 4}

K4(ON(SO3)2)2C5
{"K": 4, "O": 14, "N": 2, "S": 4, "C": 5}

This problem asks you to parse a chemical formula and count how many times each atom appears. The key challenge is handling nested parentheses and the multipliers that follow them. A stack-based approach works well: keep counts for the current scope, push a new scope when you see '(', and when you see ')', multiply the inner counts by the trailing number and merge them back into the previous scope. You also need to scan carefully for element symbols and multi-digit numbers.

END
 0