Number of Atoms

HardStackstack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a chemical formula string. An element name is an uppercase letter followed by zero or more lowercase letters. An element may be followed by a count of **2 or more**; with no count, it appears once. A group in parentheses may also be followed by a multiplier of 2 or more, which multiplies every count inside it. Groups can nest and sit next to each other, e.g. "H2O", "Mg(OH)2", "(CH3)2(OH)10". Return a string listing each element in **lexicographic order of its name**, each followed by its total count, with the count omitted when it equals 1. For example, 2 hydrogens, 1 oxygen, and 1 magnesium give "H2MgO".

Examples

Input: formula = "Mg(OH)2"
Output: "H2MgO2"
One Mg, and the group `OH` doubled gives O2 and H2. Sorted: H, Mg, O.
Input: formula = "Fe2(SO4)3"
Output: "Fe2O12S3"
Fe2, and `SO4` tripled gives S3 and O12.
Input: formula = "((Ne)2Li)3"
Output: "Li3Ne6"
Inner group gives Ne2; with Li it forms `Ne2Li`, which tripled is Ne6 and Li3.

Constraints

  • `1 <= formula.length <= 1000`
  • `formula` consists of English letters, digits, `(`, and `)`
  • `formula` is always valid, and parentheses are balanced
  • Every total count fits in a 32-bit signed integer

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More stack problems