Limited time: AI code review, hints, mock interviews, whiteboard analysis, and all Pro features are unlocked. Enroll

Number of Atoms

Hard

Topics
Hash TableStringStackSorting

Given a chemical formula (as string s), return the count of each atom. Output the element names in alphabetical order, each followed by its count if the count is greater than 1. Groups may be nested with parentheses and followed by a multiplier.

Example 1

Input:  s = "H2O"
Output: "H2O"

Example 2

Input:  s = "Mg(OH)2"
Output: "H2MgO2"

Example 3

Input:  s = "K4(ON(SO3)2)3"
Output: "K4N3O21S6"

Constraints

  • 1 <= s.length <= 16
  • s is a valid chemical formula of element tokens, digits, and parentheses.
Run ⌘' · Submit ⌘⏎
SensAI SensAI
Beta
Listening...
Tap mic to stop voice mode

Unlock AI Features

One click to activate - no payment, no credit card. Just sign in and you're in.

AI code review and hints
SensAI chat assistant
AI mock interviews
Whiteboard analysis
100% free during early access