Problem · String

Number of Atoms

Learn this problem
HardAmazonONSITE INTERVIEW
See Amazon hiring insights

Problem 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) → String

Examples

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

drafts saved locally
public String countOfAtoms(String formula) {
  // write your code here
}
formula"H2O"
expected"H2O"
checking account