KatInterview

Validate Nested Markup Tag Sequence

Stacks & QueuesAuto-graded · 19 test cases
MediumAuto-gradedStacks & Queuesstackparsingsimulation

Last 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] — where TAG is 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:

  1. Every opening tag has a corresponding closing tag of the same name.
  2. Tags are properly nested — a tag opened later must be closed before a tag opened earlier.
  3. There are no unmatched closing tags (a closing tag with no corresponding open tag).
  4. 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] where TAG matches [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.