Validate Nested Tag Expressions with Typed Bracket Rules
Stacks & QueuesAuto-graded · 19 test casesLast updated
Tests bracket matching using a stack to enforce context-sensitive nesting rules across four distinct bracket types with extra validity constraints.
Nested Tag Expression Validator
You are building a validator for a custom markup language that uses four types of bracket pairs:
| Open | Close | Type name |
|---|---|---|
( | ) | round |
[ | ] | square |
{ | } | curly |
< | > | angle |
A string is valid if and only if all of the following rules hold:
-
Proper nesting: Every opening bracket is closed by the matching closing bracket, in the correct LIFO order (no crossing).
-
Angle brackets cannot directly contain round brackets.
If(appears while the innermost enclosing bracket is<, the expression is invalid.
(Any depth of angle nesting counts — the check is: is the immediately enclosing bracket<?) -
Square brackets must contain at least one pair of curly brackets as a direct child.
"Direct child" means a bracket pair whose opening bracket appears with the square bracket as the immediately enclosing bracket.
A square bracket that closes without ever having had a{opened directly inside it is invalid. -
Curly brackets may not be nested directly inside another curly bracket.
If{appears while the immediately enclosing bracket is{, the expression is invalid. -
The expression must be fully closed (no unmatched open brackets remain at the end).
-
Unexpected closing brackets (no matching open, or wrong type) make the expression invalid.
Given a string expr containing only the characters ( ) [ ] { } < > and no other characters, return True if the expression is valid, False otherwise.
Constraints
1 ≤ len(expr) ≤ 2000exprconsists solely of the eight bracket characters()[]{}<>.- An empty string is not a valid input (length ≥ 1), but a string with no brackets at length 1 is impossible by the character constraint — all characters are brackets.
- The empty string edge case (length = 0) will not appear in test inputs, but a string of length 1 is always invalid (a lone bracket cannot be balanced).
Examples
Example 1
Input: validate_tag_expression('[{()}]')
Output: True
Example 2
Input: validate_tag_expression('[{<>}({<[{}]>})]')
Output: True
Example 3
Input: validate_tag_expression('[{}(<>)]')
Output: True
Hints
Hint 1
Use a stack where each entry records the bracket type you pushed. When you see a closing bracket, check both that the top matches and that none of the context-sensitive rules are violated at close time.
Hint 2
For rule 3, you need to track per-stack-frame whether a direct-child `{` has been opened. Consider pushing a small record (bracket type + a flag) rather than just the character.
Hint 3
Process each character once. Rules 2 and 4 fire on the *open* bracket event (check the current top of the stack). Rule 3 fires on the *close* event for `]` (check the flag for that frame before popping).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic stack-based bracket validator extended with context-sensitive rules that require tracking state per stack frame.
Data Structure
Instead of pushing just the bracket character onto the stack, we push a small record [char, has_direct_curly_child]:
char: the opening bracket character.has_direct_curly_child: a boolean flag, meaningful for[frames, that records whether at least one{was opened with this frame as the immediate parent.
Processing each character
On an opening bracket ch:
- Look at the current top of the stack (
top). - Rule 2: if
ch == '('andtop == '<'→ returnFalse. - Rule 4: if
ch == '{'andtop == '{'→ returnFalse. - If
ch == '{'andtop == '[': mark the top frame'shas_direct_curly_child = True(a direct curly child is being opened inside the square bracket). - Push
[ch, False]onto the stack.
On a closing bracket ch:
- If the stack is empty → return
False(rule 6). - Let
expected_open = MATCH[ch]. Ifstack[-1][0] != expected_open→ returnFalse(rule 1 / rule 6). - Rule 3: if
ch == ']'andstack[-1][1] == False→ returnFalse(the[never got a direct{child). - Pop the stack.
After all characters: if the stack is non-empty → return False (rule 5).
Why it is correct
- Each rule fires exactly once at the right moment: open-time checks (rules 2, 4) happen before pushing; rule 3 fires at close-time for
]before popping; rule 1/6 fires at every close. - The
has_direct_curly_childflag is set eagerly when{is opened with a[frame on top, so it is always accurate when]is encountered. - No rule interacts adversely with another; they are independent conditions on the same stack traversal.
Complexity
- Time: O(n) — one pass through the string, O(1) work per character.
- Space: O(n) — the stack can grow to at most n/2 frames in the worst case (all openers).
Worked-through examples
[{()}]→ push[, push{(marks[frame's flag = True), push(, push)closes(ok,}closes{ok,]closes[— flag is True → valid.[{}(<>)]→ push[,{(flag=True), close}, then(— top is[not<, ok, push(, push<, close>, close), close]— flag is True → valid.[{<(>)}]→ push[,{,<, then(while top is<→ invalid (rule 2).{{}}→ push{, then{while top is{→ invalid (rule 4).[{}]→ push[, push{(flag=True), close}, close]— flag True → valid.({[]})→ push(, push{, push[, push... wait[needs a direct{child.]closes[but flag is False → invalid (rule 3).
def validate_tag_expression(expr: str) -> bool:
OPENERS = set("([{<")
MATCH = {')': '(', ']': '[', '}': '{', '>': '<'}
# Stack entries: [bracket_char, has_direct_curly_child]
stack = []
for ch in expr:
if ch in OPENERS:
top = stack[-1][0] if stack else None
# Rule 2: '(' cannot appear directly inside '<'
if ch == '(' and top == '<':
return False
# Rule 4: '{' cannot appear directly inside '{'
if ch == '{' and top == '{':
return False
# If parent is '[', mark that it now has a direct curly child
if ch == '{' and top == '[':
stack[-1][1] = True
stack.append([ch, False])
else:
expected_open = MATCH[ch]
if not stack:
return False
top_char, has_curly = stack[-1]
if top_char != expected_open:
return False
# Rule 3: closing ']' requires the '[' frame to have had a direct '{' child
if ch == ']' and not has_curly:
return False
stack.pop()
# Rule 5: all brackets must be closed
return len(stack) == 0