Validate Nested Expressions with Typed Bracket Scopes
Stacks & QueuesAuto-graded · 17 test casesLast updated
Tests bracket matching with complex rules: typed pairs, mandatory ordered sub-structure inside scopes, and precedence-aware nesting constraints.
Validate Nested Expressions with Typed Bracket Scopes
You are given a string representing a structured expression used by a configuration language. The language has three types of bracket pairs:
| Open | Close | Type |
|---|---|---|
( | ) | round |
[ | ] | square |
{ | } | curly |
The string contains only these six bracket characters. A string is valid if and only if all of the following rules hold:
Rule 1 — Basic matching
Every opening bracket must be closed by the correct closing bracket of the same type, and every closing bracket must have a matching opener. No unmatched brackets are allowed.
Rule 2 — Nesting hierarchy
Brackets obey a strict containment hierarchy:
- A curly
{ }scope may directly contain round( )or square[ ]scopes (but not another curly scope directly — curly inside curly must be separated by a round or square scope). - A square
[ ]scope may directly contain round( )scopes only (no square or curly directly inside a square). - A round
( )scope may not directly contain any other scope (it must be empty or contain only other characters — but since the alphabet is only brackets, a round scope must be empty).
"Directly contains" means the inner bracket pair's opener appears as the immediate next token inside the outer scope, with no other unclosed bracket in between at the same depth level.
Rule 3 — Curly scope structure
Every curly scope must contain at least one directly-nested child scope (round or square). An empty curly {} is invalid.
Rule 4 — Square scope structure
A square scope may be empty [] or contain one or more directly-nested round ( ) children. Each directly-nested child must be a round scope.
Rule 5 — Top-level constraint
At the top level (outside all brackets), only curly scopes may appear. Any round or square bracket that opens at the top level makes the expression invalid.
Given a string s consisting solely of the characters ()[]{}, return True if the expression is valid according to all the rules above, and False otherwise.
Constraints
1 ≤ len(s) ≤ 2000sconsists only of the characters(,),[,],{,}- An empty string is not a valid input (length ≥ 1 is guaranteed), but a single character is possible.
Examples
Example 1
Input: validate_expression('{([]())}')
Output: False
Example 2
Input: validate_expression('{}')
Output: False
Example 3
Input: validate_expression('{[()()]([()])}')
Output: False
Hints
Hint 1
Use a stack to track the current open bracket and its type; when you encounter a closing bracket, check both that it matches the top of the stack and that the nesting hierarchy rule (curly > square/round, square > round only, round > nothing) is respected.
Hint 2
Track, for each stack frame, how many direct children have been opened inside it so far. When closing a curly scope, verify that at least one child was present; when closing a square scope, verify every direct child opened inside it was a round scope.
Hint 3
Handle the top-level as a virtual 'frame' that only accepts curly openers — you can model this by seeding your stack with a sentinel frame that only allows curly children, then at the end verify the sentinel's child count is consistent.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a bracket matching validator with layered structural rules. The natural tool is a stack where each frame tracks the type of the currently open scope and how many direct children have been opened inside it.
Stack frame design
Each frame is [scope_type, direct_child_count]. A sentinel frame of type 'top' is pushed before processing begins to represent the top level.
Processing each character
Opening bracket:
- Determine the
child_typebeing opened. - Look up the current parent (top of stack) and check that
child_typeis inMAY_CONTAIN[parent_type]. If not, returnFalseimmediately (hierarchy violation). - Push a new frame for
child_typewithchild_count = 0, and increment the parent'sdirect_child_countby 1.
Closing bracket:
- If the stack has only the sentinel, there is no open scope to close →
False. - If the type encoded in the closing bracket doesn't match the top frame's type →
False(mismatched bracket). - Pop the frame. Apply structural rules:
- Curly rule (Rule 3):
child_countmust be ≥ 1. - Round rule (implicit from Rule 2):
child_countmust be 0 (round scopes must be empty in this alphabet). - Square's allowed-children constraint is already enforced by
MAY_CONTAINat open time.
- Curly rule (Rule 3):
After the loop
- Exactly one frame (the sentinel) should remain; any other means unclosed brackets.
- The sentinel's
direct_child_countmust be ≥ 1 (at least one top-level curly is required; an input of only openers that were never closed would have been caught above).
Why this is correct
Every rule maps to a specific check:
- Rule 1 (basic matching): handled by type comparison on close + stack depth check.
- Rule 2 (hierarchy):
MAY_CONTAINlookup on every open. - Rule 3 (curly non-empty): child count check on curly close.
- Rule 4 (square children must be round):
MAY_CONTAIN['square'] = {'round'}enforces this at open time. - Rule 5 (top-level only curly):
MAY_CONTAIN['top'] = {'curly'}.
Complexity
- Time: O(n) — one pass over the string, O(1) work per character.
- Space: O(n) — stack depth is at most O(n) in the worst case (deeply nested).
from typing import List
def validate_expression(s: str) -> bool:
OPEN = {'(': 'round', '[': 'square', '{': 'curly'}
CLOSE = {')': 'round', ']': 'square', '}': 'curly'}
MAY_CONTAIN = {
'top': {'curly'},
'curly': {'round', 'square'},
'square': {'round'},
'round': set(),
}
stack = [['top', 0]]
for ch in s:
if ch in OPEN:
child_type = OPEN[ch]
parent_type = stack[-1][0]
if child_type not in MAY_CONTAIN[parent_type]:
return False
stack.append([child_type, 0])
stack[-2][1] += 1
elif ch in CLOSE:
close_type = CLOSE[ch]
if len(stack) < 2:
return False
if stack[-1][0] != close_type:
return False
frame_type, child_count = stack.pop()
if frame_type == 'curly' and child_count == 0:
return False
if frame_type == 'round' and child_count != 0:
return False
else:
return False
if len(stack) != 1:
return False
if stack[0][1] == 0:
return False
return True