The Number of Atoms problem gives you a chemical formula string like "H2O", "Mg(OH)2", or "K4(ON(SO3)2)2". Parse it to compute the total count of each element, accounting for nested parentheses and multipliers. Return the element counts in alphabetical order as a formatted string. This hard Number of Atoms coding problem combines stack-based expression parsing with hash map aggregation.
Apple, Microsoft, Amazon, Google, Bloomberg, and Confluent ask this because formula parsing tests advanced stack usage for nested structures — a pattern found in compilers, expression evaluators, and chemical informatics. The hash table, sorting, string, and stack interview pattern is fully exercised, and handling nested multipliers requires careful stack management.
Stack of hash maps. Maintain a stack where each entry is a hash map of element counts for the current "scope" (inside a parenthesis block). Push a new map on '(', pop and merge (with multiplier) on ')'. For each element name + count outside parentheses, add to the current top map. After processing, the final map contains all element counts. Sort alphabetically and format.
Formula: "Mg(OH)2".
Formula: "K4(ON(SO3)2)2". Nested parsing: inner "(SO3)2" → {S:2,O:6}. Merge with O:1, N:1 → {O:3,N:1,S:2}. Multiply by 2 → {O:6,N:2,S:4}. Add K:4 → {K:4,O:6,N:2,S:4}. Sorted: "K4N2O6S4".
Formula parsing with nested groups is a stack problem. The key insight: each '(' pushes a new scope; each ')' pops it and multiplies before merging into the parent scope. Practice writing the parser in three phases: (1) element name extraction, (2) count parsing, (3) parenthesis handling with stack. Test with deeply nested formulas. This parsing pattern generalizes to JSON parsing, arithmetic expression evaluation, and HTML/XML parsing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Longest Self-Contained Substring | Hard | Solve | |
| Custom Sort String | Medium | Solve | |
| Check if Strings Can be Made Equal With Operations II | Medium | Solve | |
| Brace Expansion II | Hard | Solve | |
| Valid Anagram | Easy | Solve |