Validate Nested Chemical Formula Brackets
Stacks & QueuesAuto-graded · 19 test casesLast 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 bracket | May directly contain |
|---|---|
( ) round | anything: ( ), [ ], { } |
[ ] square | only ( ) or other [ ] — not { } |
{ } curly | only ( ) — 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:
- Every opening bracket is matched by the correct closing bracket.
- The nesting constraints above are satisfied for every bracket pair.
- 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) ≤ 2000formulaconsists only of lowercase lettersa-zand 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This is a classic stack-based bracket matching problem with an added layer: we must enforce which bracket types may nest directly inside which others. The stack naturally tracks the "current parent" — the bracket that is currently open at the deepest level — which is exactly what we need to check the nesting rule.
Algorithm
- Define a
matchingdict mapping each opener to its closer, and anallowed_childrendict mapping each opener (andNonefor the top level) to the set of openers that may appear as an immediate child. - Iterate through every character in
formula:- Letter: skip.
- Opening bracket (
(,[,{): Look at the top of the stack (orNoneif empty) as the parent. If the current bracket is not inallowed_children[parent], returnFalse. Otherwise push the bracket onto the stack. - Closing bracket (
),],}): If the stack is empty, there is no matching opener — returnFalse. Pop the top; if it does not pair correctly with the current closer, returnFalse.
- After the loop, return
Trueif and only if the stack is empty (no unclosed brackets).
Why It Is Correct
- The stack always represents the chain of currently-open brackets from outermost to innermost.
- Checking
allowed_childrenat the moment of opening is sufficient: we check whether the parent (stack top) permits this bracket type as a direct child. This enforces all nesting constraints without requiring a second pass. - All three validity conditions (correct matching, correct nesting, no unclosed brackets) are covered.
Complexity
- Time: O(n) — single pass through the string.
- Space: O(n) — stack depth is at most the length of the string.
Reference Solution
def validate_formula_brackets(formula: str) -> bool:
matching = {'(': ')', '[': ']', '{': '}'}
closing = set(')}]')
allowed_children = {
None: {'(', '[', '{'},
'(': {'(', '[', '{'},
'[': {'(', '['},
'{': {'('},
}
stack = []
for ch in formula:
if ch in matching:
parent = stack[-1] if stack else None
if ch not in allowed_children[parent]:
return False
stack.append(ch)
elif ch in closing:
if not stack:
return False
top = stack.pop()
if matching[top] != ch:
return False
return len(stack) == 0
Sample Walkthrough
"(a[b(c)d]e)"—(opens at top level (ok),[opens inside((ok),(opens inside[(ok), all close correctly → True"[{ab}]"—[opens at top level (ok),{tries to open inside[, but{is not inallowed_children['[']={'(','['}→ False"({[()]})"—(opens,{opens inside((ok),[tries to open inside{, but[is not inallowed_children['{']={'('}→ False