Count Atoms in a Chemical Formula With Nested Brackets
Last updated: November 29, 2026
Quick Overview
Given a chemical formula string such as "K4[ON(SO3)2]2" with element symbols (an uppercase letter followed by optional lowercase letters), optional counts, and nested parentheses or square brackets with multipliers, return the atom counts as a canonical string sorted by element name.
0
0
0 solved
Given a chemical formula string such as "K4[ON(SO3)2]2" with element symbols (an uppercase letter followed by optional lowercase letters), optional counts, and nested parentheses or square brackets with multipliers, return the atom counts as a canonical string sorted by element name.
Google online assessments include parsing problems with recursive structure, and formula counting is a classic of the genre. The interviewer is checking a recursive descent or stack approach, correct multiplier distribution through nested groups, and strict validation of bracket matching.
What the Interviewer Expects
- Tokenizes element names as an uppercase letter plus lowercase letters
- Parses optional multi-digit counts with a default of one
- Uses recursion or a stack of counters for nested groups
- Multiplies a group's counts by the number after its closing bracket
- Validates mismatched or unclosed brackets
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Support hydrate notation like CuSO4·5H2O.
- Compute the molar mass from a periodic table map.
- Convert the recursive solution to an explicit stack to avoid recursion limits.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Elements: one uppercase letter followed by zero or more lowercase letters (
Mg,O). - Counts: optional positive integers after an element or a closing bracket; missing means 1.
- Groups: `( ... )...
High-Level Design
A recursive function group(closing) parses until it sees its closing bracket and returns a Counter. On an opening bracket it recurses, then reads the multiplier and merges the inner counts times t...