A reagent bottle's label gives its chemical formula as the string formula. It is built from:
- an element: one uppercase letter followed by zero or more lowercase letters (
H,Mg,Uue), optionally followed by a count; - a group: a formula wrapped in
(and), optionally followed by a count that multiplies everything inside it.
A count is a positive integer written with one or more digits; a missing count means 1.
Return a dictionary mapping every element name that appears to its total number of atoms.
The order of the keys does not matter. Return {} for an empty formula.
Examples
Input: formula = "NH3"
Output: {'N': 1, 'H': 3}
Input: formula = "Al2(SO4)3"
Output: {'Al': 2, 'S': 3, 'O': 12}
Input: formula = "Ca3(Fe(CN)6)2"
Output: {'Ca': 3, 'Fe': 2, 'C': 12, 'N': 12}
Explanation: inside the outer group, C and N appear 6 times each; doubled, 12.
Constraints
0 <= len(formula) <= 2 * 10**5; the formula is always well formed and groups are never empty- Groups can be nested up to 3000 levels deep, and totals can be astronomically large
- Target: time roughly proportional to the length of the formula
Goals
- Tokenise element names and multi-digit counts by scanning characters
- Use a stack of tallies, one per open group, and fold a group into its parent when it closes
- Avoid expanding repeated groups as text, which grows exponentially