Validate Nested Chemical Formula Expressions
Stacks & QueuesAuto-graded · 19 test casesLast updated
Tests deep bracket-matching with multiplicative expansion rules by validating and evaluating a chemical-formula-style string with nested parentheses and numeric multipliers.
Validate and Evaluate a Chemical Expression
A chemical expression is a string built from the following grammar:
expr ::= term+
term ::= group | atom
group ::= '(' expr ')' multiplier
| '[' expr ']' multiplier
| '{' expr '}' multiplier
atom ::= UPPER LOWER? multiplier
multiplier ::= DIGIT+ (one or more digits, no leading zeros UNLESS the value is exactly 0 — which is forbidden)
| ε (empty, implying a count of 1)
UPPER ::= 'A'–'Z'
LOWER ::= 'a'–'z'
DIGIT ::= '0'–'9'
Rules and definitions:
- Atoms start with one uppercase letter optionally followed by one lowercase letter (e.g.
H,Fe,Na). - Multipliers following a group or atom are one or more decimal digits with no leading zeros (e.g.
2,12are valid;02is invalid). A missing multiplier means1. - Brackets must match by type:
(with),[with],{with}. Mismatched pairs (e.g.(]) make the expression invalid. - Every open bracket must be closed and every close bracket must have a matching open bracket.
- Multipliers of zero are forbidden (a multiplier of
0or any multi-digit string that equals0padded, like00, makes the expression invalid). - An empty bracket pair (e.g.
(),[],{}) is invalid — each group must contain at least one term. - The top-level expression must contain at least one atom.
- A trailing multiplier may not appear at the very start of the string (i.e., the string cannot begin with a digit).
- Any character that is not
A-Z,a-z,0-9,(,),[,],{,}makes the expression invalid.
Given an expression string formula, return a dictionary mapping each atom name to its total count after fully expanding all groups, if the formula is valid. If the formula is invalid for any reason, return an empty dictionary {}.
Atom names in the returned dictionary follow the UPPER LOWER? convention (e.g. "H", "Fe").
Constraints
1 ≤ len(formula) ≤ 2000- The string contains only printable ASCII characters.
- Atom counts in a valid formula are always positive integers; no single expanded atom count will exceed
10^9. - Bracket nesting depth will not exceed
50.
Examples
Example 1
Input: evaluate_formula('H2O')
Output: {'H': 2, 'O': 1}
Example 2
Input: evaluate_formula('Fe2(SO4)3')
Output: {'Fe': 2, 'S': 3, 'O': 12}
Example 3
Input: evaluate_formula('(Ca[OH]2)3')
Output: {'Ca': 3, 'O': 6, 'H': 6}
Hints
Hint 1
Use a stack of dictionaries — push a fresh dict when you open a bracket, then pop and merge (scaled by the multiplier) when you close the matching bracket.
Hint 2
Parse left-to-right with an index pointer: consume an atom (uppercase + optional lowercase + optional digits), or a bracket open/close, carefully reading any digit run that follows a closing bracket or atom.
Hint 3
Track what bracket type opened each level (store it alongside the running dict on the stack) so you can detect type mismatches on close; also validate no-leading-zeros and no-zero multiplier as you parse the digit run.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
High-level idea
Parse the formula left-to-right with a single index pointer i and a stack of (open_bracket, running_dict) pairs. Each stack frame accumulates atom counts for one nesting level.
| Event | Action |
|---|---|
Open bracket ([{ | Push a fresh frame onto the stack |
Close bracket )]} | Pop the top frame; verify bracket type matches; read the optional multiplier; merge scaled counts into the frame below |
| Uppercase letter | Parse atom (upper + optional lower), read optional multiplier, add to top frame |
| Anything else at top level | Invalid → return {} |
Validation checks woven in during parsing
- Character set: any non-
[A-Za-z0-9()[\]{}]character → invalid immediately (pre-scan). - Leading digit: if
formula[0].isdigit()→ invalid. - Bracket type mismatch: when closing, the stored open bracket must match the expected counterpart.
- Unmatched brackets: a close with only the sentinel frame → invalid; stack depth > 1 after consuming all input → invalid.
- Empty groups: after closing a bracket, if the popped dict is empty → invalid.
- Zero multiplier: if the parsed integer is 0 → invalid.
- Leading zeros in multiplier: digit run of length > 1 starting with
'0'→ invalid. - Orphaned lowercase / digit: a lowercase letter not preceded by an uppercase letter, or a digit not preceded by an atom/close → invalid (handled by falling through to
return {}).
Why it is correct
The grammar is LL(1): at every position the next character uniquely determines which production to apply. The stack mirrors the recursive structure of expr → term+. Merging with a factor when popping exactly implements the distributive semantics of a multiplier over a group. All validity constraints are checked at the earliest point they can be detected.
Complexity
- Time: O(n · d) where n =
len(formula)and d = nesting depth (≤ 50), because each merge may iterate over the atoms accumulated in the popped frame. In practice O(n) since d and alphabet size are both bounded constants. - Space: O(n) for the stack (each character can open at most one frame).
from typing import Dict
def evaluate_formula(formula: str) -> Dict[str, int]:
OPEN = {'(', '[', '{'}
CLOSE = {')', ']', '}'}
MATCH = {')': '(', ']': '[', '}': '{'}
def merge(target: dict, source: dict, factor: int):
for k, v in source.items():
target[k] = target.get(k, 0) + v * factor
n = len(formula)
i = 0
if n == 0 or formula[0].isdigit():
return {}
for ch in formula:
if not (ch.isalpha() or ch.isdigit() or ch in '()[]{}'):
return {}
# Stack holds (open_bracket_char, running_dict)
stack = [('', {})] # sentinel level
while i < n:
ch = formula[i]
if ch in OPEN:
stack.append((ch, {}))
i += 1
elif ch in CLOSE:
if len(stack) <= 1:
return {}
open_ch, current = stack.pop()
if open_ch != MATCH[ch]:
return {}
if not current:
return {}
i += 1
j = i
while i < n and formula[i].isdigit():
i += 1
if i > j:
num_str = formula[j:i]
if len(num_str) > 1 and num_str[0] == '0':
return {}
factor = int(num_str)
if factor == 0:
return {}
else:
factor = 1
merge(stack[-1][1], current, factor)
elif ch.isupper():
atom = ch
i += 1
if i < n and formula[i].islower():
atom += formula[i]
i += 1
j = i
while i < n and formula[i].isdigit():
i += 1
if i > j:
num_str = formula[j:i]
if len(num_str) > 1 and num_str[0] == '0':
return {}
factor = int(num_str)
if factor == 0:
return {}
else:
factor = 1
stack[-1][1][atom] = stack[-1][1].get(atom, 0) + factor
elif ch.islower():
return {}
elif ch.isdigit():
return {}
else:
return {}
if len(stack) != 1:
return {}
result = stack[0][1]
if not result:
return {}
return result