Validate Nested Tag Pairs in a Markup String
Stacks & QueuesAuto-graded · 18 test casesLast updated
Tests whether candidates can simulate bracket-matching logic with named tags, enforcing strict open/close pairing and proper nesting order.
Validate Nested Tag Pairs in a Markup String
You are given a string representing a simplified markup document. The document contains named tags of two forms:
- Opening tag:
[TAG](e.g.[div],[b],[section]) - Closing tag:
[/TAG](e.g.[/div],[/b],[/section])
Tag names consist only of lowercase English letters (a–z). Everything outside of [...] brackets is plain text and should be ignored.
A document is valid if and only if all of the following hold:
- Every opening tag has a corresponding closing tag.
- Every closing tag has a corresponding opening tag.
- Tags are properly nested — a tag opened later must be closed before a tag opened earlier (last-in, first-out order).
- There are no malformed bracket sequences: every
[is eventually followed by a]on the same "token" (you may assume the input never has a[inside another[, but a[with no matching]makes the document invalid).
Return True if the document is valid, False otherwise.
Notes
- Tag names are case-sensitive as given, but the problem guarantees all tag characters are lowercase, so no special casing is needed.
- An empty string (or a string with no tags at all) is considered valid.
- A closing tag with no matching open tag on the stack is immediately invalid.
- Leftover unclosed tags at the end make the document invalid.
Constraints
0 ≤ len(s) ≤ 2000- Tag names are 1–20 lowercase English letters.
- The string may contain any printable ASCII characters outside of tags.
- A
[with no subsequent]before the next[or end-of-string is a malformed token and the document is invalid.
Examples
Example 1
Input: validate_tags('[div]Hello[/div]')
Output: True
Example 2
Input: validate_tags('[outer][inner]text[/outer][/inner]')
Output: False
Example 3
Input: validate_tags('No tags here at all!')
Output: True
Hints
Hint 1
Use a stack to track currently open tags — push on an opening tag, pop and verify on a closing tag.
Hint 2
When you encounter a '[', scan forward to find the matching ']'. If none exists before the next '[' or end of string, return False immediately.
Hint 3
After processing all tokens, the document is valid only if the stack is empty (every opened tag was closed).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic stack-based bracket matching problem, extended to named tokens.
Algorithm
- Scan the string character by character. When a
[is found, locate the matching]by scanning forward. If we hit another[or end-of-string first, the token is malformed — returnFalse. - Classify the token (contents between
[and]):- If it starts with
/, it is a closing tag. Check that the stack is non-empty and the top equals the tag name. If not, returnFalse. Otherwise, pop the stack. - Otherwise it is an opening tag. Push the tag name onto the stack.
- If it starts with
- After the full string is processed, return
Trueonly if the stack is empty (no unclosed tags remain).
Why it is correct
The stack enforces LIFO (last-in, first-out) nesting. Mismatched or out-of-order closing tags are caught at step 2, malformed tokens at step 1, and unclosed tags at step 3. Plain text between tags is skipped harmlessly.
Edge cases handled
- Empty string → stack starts and ends empty →
True. - String with no tags → no pushes/pops →
True. - Extra closing tag → stack empty on pop attempt →
False. - Malformed
[no close→ scan exits at end-of-string without finding]→False. []or[/](empty tag name) → explicitly rejected.
Complexity
- Time: O(n) — each character is visited at most twice (outer scan + inner scan for the closing
]). - Space: O(d) where d is the maximum nesting depth (stack size). In the worst case O(n).
def validate_tags(s: str) -> bool:
stack = []
i = 0
n = len(s)
while i < n:
if s[i] == '[':
# Find the closing ']'
j = i + 1
while j < n and s[j] != ']' and s[j] != '[':
j += 1
# If we hit end-of-string or another '[' without finding ']', malformed
if j >= n or s[j] != ']':
return False
token = s[i+1:j] # content between brackets
if token.startswith('/'):
tag_name = token[1:]
if not tag_name: # [/] with empty name is invalid
return False
if not stack or stack[-1] != tag_name:
return False
stack.pop()
else:
if not token: # [] with empty name is invalid
return False
stack.append(token)
i = j + 1
else:
i += 1
return len(stack) == 0