KatInterview

Validate Nested Chemical Formula Brackets

Stacks & QueuesAuto-graded · 19 test cases
EasyAuto-gradedStacks & Queuesstacksbracket matchingsimulation

Last updated

Tests bracket matching with domain-specific pairing rules where round, square, and curly brackets each have distinct valid nesting constraints.

Validate Nested Chemical Formula Brackets

A chemistry notation system uses three types of bracket pairs to group atoms and sub-structures. The system has strict rules about which bracket types may be directly nested inside which other bracket types:

Outer bracketMay directly contain
( ) roundanything: ( ), [ ], { }
[ ] squareonly ( ) or other [ ] — not { }
{ } curlyonly ( ) — not [ ] or { }

In other words:

  • Curly {} is the most restrictive: its immediate children may only be round ().
  • Square [] is mid-level: its immediate children may be round () or square [], but not curly {}.
  • Round () is unrestricted: its immediate children may be any bracket type.

"Immediate child" means a bracket pair whose opening bracket is directly inside the outer pair (i.e., the nesting depth increases by exactly one when entering it).

Given a string formula that contains only the characters (, ), [, ], {, }, and lowercase letters a-z, determine whether the bracket structure is valid according to these rules.

A bracket structure is valid if and only if:

  1. Every opening bracket is matched by the correct closing bracket.
  2. The nesting constraints above are satisfied for every bracket pair.
  3. Non-bracket characters (a-z) are ignored for the purpose of validation.

Return True if the formula is valid, False otherwise.

An empty string (or a string with only letters) is considered valid.

Constraints

  • 0 ≤ len(formula) ≤ 2000
  • formula consists only of lowercase letters a-z and the characters ( ) [ ] { }
  • Nesting can be arbitrarily deep within the length limit

Examples

Example 1

Input: validate_formula_brackets('(a[b(c)d]e)')

Output: True

Example 2

Input: validate_formula_brackets('[{ab}]')

Output: False

Example 3

Input: validate_formula_brackets('({[()]})')

Output: False

Hints

Hint 1

Use a stack to track the sequence of currently open brackets. When you see a closing bracket, check both that it matches the top of the stack and that the parent bracket (one level further down) allows this bracket type as an immediate child.

Hint 2

Define the allowed-children relationship as a dictionary or function. When you open a new bracket, the bracket currently on top of the stack is its parent — check the constraint before pushing.

Hint 3

Edge cases: an empty stack when a closing bracket is seen means unmatched closing bracket (invalid); a non-empty stack at the end means unclosed brackets (invalid). A completely empty formula or one with only letters is valid.