Number of Atoms - Problem

Imagine you're a chemist working with complex molecular formulas and need to count how many atoms of each element are present. Your task is to parse a chemical formula string and return the count of each atom type.

The formula follows these rules:

  • Atomic elements start with an uppercase letter, followed by zero or more lowercase letters (e.g., H, Mg, Ca)
  • Counts appear as digits after the element name. If no digits appear, the count is 1
  • Parentheses group elements together, and can have a multiplier after the closing parenthesis
  • Formulas can be concatenated: H2O2He3Mg4 is valid

Goal: Return a string with all elements in alphabetical order, followed by their counts (if > 1).

Examples:

  • "H2O""H2O"
  • "Mg(OH)2""H2MgO2"
  • "K4(ON(SO3)2)2""K4N2O14S4"

Input & Output

example_1.py — Simple Formula
$ Input: formula = "H2O"
Output: "H2O"
💡 Note: The formula contains 2 hydrogen atoms and 1 oxygen atom. Since oxygen count is 1, it's omitted in the result.
example_2.py — Formula with Parentheses
$ Input: formula = "Mg(OH)2"
Output: "H2MgO2"
💡 Note: The (OH) group is multiplied by 2, giving us 2 oxygen and 2 hydrogen atoms, plus 1 magnesium atom. Sorted alphabetically: H2MgO2.
example_3.py — Complex Nested Formula
$ Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
💡 Note: Breaking down: K4 + (ON(SO3)2)2. The inner (SO3)2 gives S2O6, then ON(S2O6) = ONS2O6, and finally (ONS2O6)2 = O2N2S4O12 = N2O14S4. Combined with K4 gives K4N2O14S4.

Constraints

  • 1 ≤ formula.length ≤ 1000
  • formula consists of English letters, digits, '(', and ')'
  • formula is always valid
  • All atom names consist of lowercase letters, except the first character which is uppercase
  • The sum of all atoms will fit in a 32-bit integer

Visualization

Tap to expand
Chemical Formula Stack ParserStack of ScopesBase ScopeK: 4, N: 2, O: 2Sub-Scope (popped)O: 1, N: 1 → ×2Parsing ProcessInput: K4(ON)21Parse 'K4' → Add to base scope2Encounter '(' → Push new scope3Parse 'O' → Add to sub-scope4Parse 'N' → Add to sub-scope5Encounter ')2' → Pop & multiply by 26Merge: O×2=2, N×2=2 into base7Sort & format: K4N2O2Algorithm Benefits✓ Single pass parsing✓ O(n) time complexity✓ Handles deep nesting✓ Memory efficient
Understanding the Visualization
1
Initialize Base Kitchen
Start with main recipe book (hash map) on the counter
2
Collect Main Ingredients
Add direct ingredients like K4 to main recipe
3
Start Sub-Recipe
When encountering '(', open new recipe book for the sub-recipe
4
Collect Sub-Ingredients
Add ingredients like O, N to the sub-recipe book
5
Complete Sub-Recipe
When encountering ')2', multiply all sub-recipe ingredients by 2
6
Merge Back
Combine multiplied sub-recipe ingredients into main recipe book
7
Final Inventory
Sort all ingredients alphabetically and format the result
Key Takeaway
🎯 Key Insight: Use a stack to mirror the nested structure of parentheses - each opening creates a new scope, each closing multiplies and merges back to the parent scope, enabling efficient single-pass parsing of complex chemical formulas.
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen