Ctrl K

Element Tally From a Formula

Hard
You are given a chemical formula compound, built by these rules: - an element name is an uppercase Latin letter optionally followed by lowercase letters (H, Mg, Uuo); - an element may be followed by a count, an integer of at least 2 with no leading zeros; with no count, the element appears once; - formulas can be written one after another: H2O2Na is a formula too; - a non-empty formula can be wrapped in parentheses, and the closing parenthesis may be followed by a count under the same rules: (OH)2 means the group is repeated twice. Count how many atoms of each element the formula contains and return the result as a string: elements in alphabetical order (ordinary string comparison), each followed by its count if that count is greater than 1.
Example 1
compound="C2H5OH" → 'C2H6O'

Carbon 2, hydrogen 5 + 1 = 6, oxygen 1. Alphabetically: C, H, O; the count 1 for oxygen is omitted.

Example 2
compound="Ca3(PO4)2" → 'Ca3O8P2'

The PO4 group appears twice: 2 phosphorus and 8 oxygen. Plus 3 calcium.

Example 3
compound="Fe((OH)2Cl)3" → 'Cl3FeH6O6'

The inner OH group is doubled, then the whole outer group is tripled: 6 oxygen, 6 hydrogen, 3 chlorine and 1 iron.

Constraints
  • 1 ≤ len(compound) ≤ 1000
  • compound consists of Latin letters, digits and parentheses and follows the rules above
  • Every element's atom count is below 2³¹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEqual Letters Kept Apart HardA Calculator With Brackets and Variables HardSimplify a Letter Polynomial HardShowcase: Profit Plus Variety HardAnagram Buckets Medium
loading Python…
Input
compound="C2H5OH"
Expected
'C2H6O'

Run checks the first 3 tests in your browser. Submit checks all 176 tests on the server, hidden ones included.