Validate Nested Markup Tag Sequence
Stacks & QueuesAuto-graded · 19 test casesLast updated
Tests bracket matching logic by verifying that a simplified markup string with typed opening/closing tags is correctly nested and properly closed.
Validate Nested Markup Tag Sequence
You are given a string representing a simplified markup document. The markup uses named tags of the form:
- Opening tag:
[TAG]— whereTAGis a non-empty string of uppercase letters only (e.g.[B],[SECTION]). - Closing tag:
[/TAG]— the same name prefixed with/(e.g.[/B],[/SECTION]).
Any characters outside of tags (i.e. not part of a [...] construct) are treated as plain text and are ignored during validation.
A markup string is valid if and only if:
- Every opening tag has a corresponding closing tag of the same name.
- Tags are properly nested — a tag opened later must be closed before a tag opened earlier.
- There are no unmatched closing tags (a closing tag with no corresponding open tag).
- All opened tags are eventually closed by the end of the string.
The string may contain malformed bracket constructs — anything inside [...] that is not a valid opening or closing tag (e.g. [123], [b] lowercase, [], [/], [A B]) must be treated as plain text and ignored.
Return True if the markup is valid, False otherwise.
Constraints
0 <= len(s) <= 2000- The string contains only printable ASCII characters.
- Tag names consist of uppercase Latin letters only (
A–Z), length between 1 and 20 characters. - A valid tag token is exactly
[TAG]or[/TAG]whereTAGmatches[A-Z]{1,20}. - Anything that does not match those two patterns exactly is ignored.
- An empty string is considered valid (returns
True).
Examples
Example 1
Input: validate_markup('[A][B]hello[/B][/A]')
Output: True
Example 2
Input: validate_markup('[A][B][/A][/B]')
Output: False
Example 3
Input: validate_markup('[DIV][SPAN]text[/SPAN][/DIV][FOOTER][/FOOTER]')
Output: True
Hints
Hint 1
Use a stack: push tag names for opening tags, and for closing tags check whether the stack's top matches before popping.
Hint 2
Use a regular expression to extract only valid tag tokens from the string, ignoring all malformed bracket content and plain text.
Hint 3
After processing all tokens, the markup is valid only if the stack is empty — any unclosed opening tag makes it invalid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This is a classic bracket-matching problem, but instead of single characters like ( and ), the "brackets" are named tags that must match by name. The stack-based approach generalises directly.
Algorithm
-
Extract valid tokens only using a regular expression
\[(/?)([A-Z]{1,20})\]. This precisely matches only strings of the form[TAG]or[/TAG]where the tag name is 1–20 uppercase letters. Every other bracket-like construct (e.g.[123],[abc],[A B],[],[/]) fails the regex and is silently skipped. -
Process each token:
- If it is an opening tag
[TAG], pushTAGonto the stack. - If it is a closing tag
[/TAG]:- If the stack is empty, there is no matching open tag → return
False. - If the top of the stack is not
TAG, the nesting is wrong → returnFalse. - Otherwise, pop the stack (matched successfully).
- If the stack is empty, there is no matching open tag → return
- If it is an opening tag
-
After all tokens, the string is valid if and only if the stack is empty (all opened tags were closed).
Correctness
- Rule 1 (every open has a close) and Rule 4 (all opened tags closed) → enforced by checking
len(stack) == 0at the end. - Rule 2 (proper nesting) → enforced by requiring the stack top to match the closing tag name.
- Rule 3 (no unmatched closing tags) → enforced by checking
not stackbefore popping. - Malformed tokens → the regex only extracts perfectly-formed tags; everything else is invisible.
Complexity
- Time: O(n) where n = len(s). The regex scans the string once; each token is processed in O(1) amortised stack operations.
- Space: O(d) where d is the maximum nesting depth (bounded by n/2).
import re
def validate_markup(s: str) -> bool:
# Match only valid opening or closing tags: [A-Z]{1,20} or /[A-Z]{1,20}
token_pattern = re.compile(r'\[(/?)([A-Z]{1,20})\]')
stack = []
for match in token_pattern.finditer(s):
slash, name = match.group(1), match.group(2)
if slash == '':
# Opening tag
stack.append(name)
else:
# Closing tag
if not stack or stack[-1] != name:
return False
stack.pop()
return len(stack) == 0