
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							Atoms in a Chemical Formula
								Certification: Advanced Level
								Accuracy: 0%
								Submissions: 0
								Points: 15
							
							Write a C++ program to count the number of atoms in a valid chemical formula.
Example 1
- Input: formula = "H2O"
- Output: "H:2 O:1"
- Explanation:
    - The formula contains two hydrogen atoms and one oxygen atom.
 
Example 2
- Input: formula = "Mg(OH)2"
- Output: "H:2 Mg:1 O:2"
- Explanation:
    - The formula contains:
- One magnesium atom (Mg)
- Two hydrogen atoms (H) - one inside the parentheses multiplied by 2
- Two oxygen atoms (O) - one inside the parentheses multiplied by 2
 
Constraints
- 1 ≤ formula.length ≤ 1000
- Only valid chemical formulas will be used as input
- Time Complexity: O(n²) where n is the length of the formula
- Space Complexity: O(n)
Editorial
									
												
My Submissions
										All Solutions
									| Lang | Status | Date | Code | 
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code | 
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use a stack to handle nested parentheses
- Process the formula from right to left or use recursion
- Use a map to store the count of each atom
- Remember to handle the multipliers correctly for atoms inside parentheses
- Sort the output alphabetically according to atom names
