Leetcode 726. Number of Atoms
Parse a chemical formula with multi-letter element names, numeric multipliers, and nested parentheses to compute the total count of each atom, correctly propagating multipliers through nested scopes. Output the atom counts in lexicographic order in the specified compact string format.
Asked at:
Agoda
Question Timeline
See when this question was last asked and where, including any notes left by other candidates.
Early December, 2025
Agoda
Staff
Given a string `formula` representing a chemical formula, return the **total mass** of the molecule assuming the following atomic weights: `C = 12`, `H = 4`, `O = 1`. The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name. One or more digits representing that element's count may follow if the count is greater than `1`; if the count is `1`, no digits will follow. Two formulas can be concatenated together to produce another formula, and a formula placed in parentheses with an optional count is also a formula. You must first determine the count of each atom as in “Number of Atoms”, then compute: - `mass = 12 * count('C') + 4 * count('H') + 1 * count('O')` and return this mass as an integer. **Examples** - Input: `formula = "H2O"` Output: `9` Explanation: counts are `{'H': 2, 'O': 1}` so mass is `4 * 2 + 1 * 1 = 9`. - Input: `formula = "C6H12O6"` Output: `120` Explanation: counts are `{'C': 6, 'H': 12, 'O': 6}`, mass is `12 * 6 + 4 * 12 + 1 * 6 = 120`. **Constraints** - `1 <= formula.length <= 1000` - `formula` consists of English letters, digits, `'('`, and `')'`. - `formula` is always valid.
Hello Interview Premium
Your account is free and you can post anonymously if you choose.