KatInterview

Validate Nested Tag Pairs in a Markup String

Stacks & QueuesAuto-graded · 18 test cases
EasyAuto-gradedStacks & Queuesstacksbracket matchingparsing

Last 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:

  1. Every opening tag has a corresponding closing tag.
  2. Every closing tag has a corresponding opening tag.
  3. Tags are properly nested — a tag opened later must be closed before a tag opened earlier (last-in, first-out order).
  4. 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).