Number of Atoms

Hard · Stack & Strings · Hash Table · String · Stack · Sorting

Problem

You are given a chemical formula as a string. Return how many of each atom it contains.

Return a string listing every atom name in sorted order (by character code, so "B" comes before "Be" and "Ca"), each followed by its total count when that count is more than 1.

Examples

Input: formula = "H2SO4"
Output: "H2O4S"

Two hydrogen, four oxygen and one sulfur atom, listed in sorted order.

Input: formula = "Fe2(SO4)3"
Output: "Fe2O12S3"

The group SO4 is taken three times: 3 sulfur and 12 oxygen.

Input: formula = "(OH)2Ca"
Output: "CaH2O2"

The OH group is doubled, and Ca appears once.

Constraints

Approaches

Follow-up

What if you needed one number, such as the formula's weight, rather than a listing? The right-to-left scan can add weight · count · product per atom without building any map; see the use case "Total weight of a formula".

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…