Problem · String
Number of Atoms
Learn this problemProblem statement
You are given a valid chemical formula string. Return the count of each atom as one canonical string.
An atom name starts with an uppercase letter and may be followed by lowercase letters. A number after an atom or a parenthesized group multiplies that atom or group. If no number follows, the multiplier is 1. Parentheses may be nested.
The output must list atom names in lexicographic order. For each atom, write the atom name followed by its count only when the count is greater than 1.
Function
countOfAtoms(formula: String) → StringExamples
Example 1
formula = "H2O"return = "H2O"There are two hydrogen atoms and one oxygen atom. The count for oxygen is omitted because it is 1.
Example 2
formula = "Mg(OH)2"return = "H2MgO2"The group (OH) is multiplied by 2, so the total counts are H:2, Mg:1, and O:2. Atom names are emitted in lexicographic order.
Constraints
- The formula is valid and contains atom names, positive integer multipliers, and parentheses.
- Parentheses may be nested.
More Amazon problems
- Secure Maximum DeliveriesOA · Seen Jul 2026
- Find Median from Data StreamONSITE INTERVIEW · Seen Jul 2026
- Handwritten SigmoidPHONE SCREEN · Seen Jul 2026
- Handwritten SoftmaxPHONE SCREEN · Seen Jul 2026
- Koko Eating BananasONSITE INTERVIEW · Seen Jul 2026
- Loyal Customers Across Two DaysONSITE INTERVIEW · Seen Jul 2026
- Maximum System Memory CapacityOA · Seen Jul 2026
- Package Delivery SystemOA · Seen Jul 2026