KatInterview

Validate Nested Chemical Formula Expressions

Stacks & QueuesAuto-graded · 19 test cases
HardAuto-gradedStacks & Queuesstacksbracket matchingparsing

Last 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:

  1. Atoms start with one uppercase letter optionally followed by one lowercase letter (e.g. H, Fe, Na).
  2. Multipliers following a group or atom are one or more decimal digits with no leading zeros (e.g. 2, 12 are valid; 02 is invalid). A missing multiplier means 1.
  3. Brackets must match by type: ( with ), [ with ], { with }. Mismatched pairs (e.g. (]) make the expression invalid.
  4. Every open bracket must be closed and every close bracket must have a matching open bracket.
  5. Multipliers of zero are forbidden (a multiplier of 0 or any multi-digit string that equals 0 padded, like 00, makes the expression invalid).
  6. An empty bracket pair (e.g. (), [], {}) is invalid — each group must contain at least one term.
  7. The top-level expression must contain at least one atom.
  8. A trailing multiplier may not appear at the very start of the string (i.e., the string cannot begin with a digit).
  9. 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.