Tutorialspoint
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)
MapStackTutorialspointIBM
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Use a stack to manage nested formulas
 Step 2: Read formula left to right and parse atoms, counts, and parentheses
 Step 3: Multiply inner atoms by surrounding counts
 Step 4: Merge nested counts to the outer level
 Step 5: Sort atoms alphabetically for output
 Step 6: Build and return formatted result string

Submitted Code :