FastPrepNumber of Atoms
Problems/Number of Atoms

Number of Atoms

Amazon logoAmazon● HardONSITE INTERVIEW
QuestionFunctionExamplesConstraints

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

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
public String countOfAtoms(String formula) {
  // write your code here
}
Checking account…