FunctionRacerProblemsRace

Atoms in a Hydrate Formula

HardStacks and queuesPython, JavaScript, TypeScript, Java, C++

formula describes a chemical compound. Count the atoms of each element in it:

Return every element once, in alphabetical order (plain string order, so C comes before Ca), each followed by its total count when that count is more than 1. For CuSO4.5H2O the answer is "CuH10O9S".

Example 1

formula "CuSO4.5H2O"
returns "CuH10O9S"

CuSO4 gives one Cu, one S and 4 O, and five H2O give 10 H and 5 more O.

Example 2

formula "[Co(NH3)6]Cl3"
returns "Cl3CoH18N6"

(NH3)6 gives 6 N and 18 H. Add one Co and 3 Cl, and sort the names: Cl, Co, H, N.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Stacks and queues problems