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:
H2O2He3Mg4is 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code