Problem 591

Abstract / Summary

Check if a string of nested tags is properly opened closed and nested without invalid sequences.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0591.py

class Solution:
    def isValid(self, code: str) -> bool:
        # code must be wrapped in a tag
        if len(code) < 2:
            return False
        if code[0] != "<" or code[-1] != ">":
            return False

        size    = len(code)
        comment = False
        close   = [] # stack
        skip    = 0  # ignore these characters

        for i in range(size):
            next = code[i :]

            # skip because its still a closing tag
            if skip > 0:
                skip -= 1
                continue

            if not close and i > 0:
                return False # outermost tag closed too early

            # comment
            if comment:
                if next.startswith("]]>"):
                    comment = False
                    skip    = len(close.pop()) - 1
                continue

            if next.startswith("<![CDATA["):
                comment = True
                close.append("]]>")
                skip = 8 # len("<![CDATA[") - 1
                continue

            # close a tag
            if close and next.startswith(close[-1]):
                skip = len(close.pop()) - 1
                continue

            if next[0] != "<":
                continue

            # open a new tag
            stop = next.find(">")
            # each "<" needs a ">" (which isn't clear from the description)
            if stop == -1:
                return False
            # create its closing tag
            tag = next[1 : stop]
            # uppercase only, 1..9 characters
            if not tag.isupper() or not tag.isalpha() or not (1 <= len(tag) <= 9):
                return False

            skip = stop
            close.append("</" + tag + ">")

        # stack must be empty => all tags closed
        return not close
61 lines | 1858 bytes | submitted July 10, 2024 | GitHub   31% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (50k+ submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The isValid method determines whether a string representing a simplified markup document conforms to a strict set of syntactic rules. The document must consist of a single top-level element, may contain nested elements, and can embed CDATA sections that are treated as opaque text. The implementation walks the input once, maintaining a stack of expected closing tags and a few state flags that guide how each character sequence is interpreted.

Initial Validation

Before any parsing begins the routine checks that the input is at least two characters long and that it starts with “<” and ends with “>”. These conditions guarantee that the outermost construct can possibly be a well-formed tag.

if len(code) < 2:
    return False
if code[0] != "<" or code[-1] != ">":
    return False

If either test fails the function returns immediately, preventing unnecessary work on obviously malformed strings.

Core Loop Variables

Three mutable variables drive the scan:

  • comment - a Boolean that indicates whether the current position lies inside a CDATA block.
  • close - a list used as a stack that stores the exact closing tag strings expected next.
  • skip - an integer counter that tells the loop how many characters to ignore because they belong to a tag that has already been processed.

These variables are updated in a deterministic fashion, ensuring that each character of the input is examined at most once.

CDATA Section Handling

When the parser encounters the literal sequence <![CDATA[, it switches into CDATA mode. In this mode all characters are ignored until the terminating sequence ]]> appears. The closing delimiter is pushed onto the close stack so that the same skipping logic used for normal tags can be reused.

if next.startswith("<![CDATA["):
    comment = True
    close.append("]]>")
    skip = 8                     # length of "<![CDATA[" minus one
    continue

While comment is true, the only check performed is whether the remaining substring starts with ]]>. Upon finding it, the flag is cleared, the corresponding closing marker is popped from the stack, and the skip counter is set to the length of that marker minus one, causing the loop to bypass the characters that form the terminator.

if comment:
    if next.startswith("]]>"):
        comment = False
        skip    = len(close.pop()) - 1
    continue

Skipping Process

The skip counter is decremented on each iteration when it is positive, and the loop body is bypassed. This mechanism prevents the parser from re-examining characters that belong to a tag that has already been recognized, whether it is an opening tag, a closing tag, or a CDATA terminator.

if skip > 0:
    skip -= 1
    continue

Closing Tag Detection

If the stack is non-empty and the current substring begins with the expected closing tag (the element at the top of close), the parser treats it as a successful match. The matched tag is removed from the stack and skip is set to the length of the closing tag minus one, so the loop advances past the entire closing construct.

if close and next.startswith(close[-1]):
    skip = len(close.pop()) - 1
    continue

An additional guard ensures that no characters appear after the outermost tag has been closed. If the stack is empty and the current index is beyond the first character, the function returns False, because any further content would violate the single-root requirement.

if not close and i > 0:
    return False

Opening Tag Processing

When the current character is “<” and none of the earlier special cases apply, the parser treats it as the start of a new element. It searches for the next “>” to delimit the tag name. If no closing bracket is found, the input is rejected.

stop = next.find(">")
if stop == -1:
    return False

The substring between the brackets becomes the candidate tag name. The implementation enforces three constraints: the name must consist solely of uppercase alphabetic characters, its length must be between one and nine inclusive, and it must contain no other symbols. Failure to meet any of these rules results in an immediate False.

tag = next[1 : stop]
if not tag.isupper() or not tag.isalpha() or not (1 <= len(tag) <= 9):
    return False

A matching closing tag string is constructed by prefixing "</" and suffixing ">". This string is pushed onto the close stack, and skip is set to the distance from the opening “<” to the closing “>”, effectively moving the cursor past the entire opening tag.

skip = stop
close.append("</" + tag + ">")

Final Stack Check

After the loop finishes, the method returns True only if the close stack is empty, indicating that every opening tag has been paired with a corresponding closing tag and that no stray CDATA terminators remain.

return not close

Edge Cases Addressed

The algorithm explicitly handles several subtle situations:

  • An input that lacks a surrounding pair of angle brackets is rejected early.
  • A CDATA block that is not properly closed with ]]> causes the parser to remain in comment mode, leading to a final non-empty stack and a False result.
  • Tags with illegal characters, mixed case, or length outside the 1-9 range are filtered out before they can affect the stack.
  • Nested tags are correctly matched because each opening tag pushes its expected closing counterpart, and the stack ensures LIFO ordering.
  • Content appearing after the outermost closing tag triggers the early-exit guard, preserving the single-root invariant.
  • Missing closing brackets for an opening tag are caught by the find(">") check, preventing the parser from reading beyond the string bounds.

Performance Optimizations

The implementation achieves linear traversal by advancing the index only once per character, with the skip counter allowing whole tag sequences to be bypassed without additional per-character checks. The use of a Python list as a stack provides amortized constant-time push and pop operations. Early returns on clearly invalid conditions (such as missing angle brackets or illegal tag names) avoid unnecessary processing of the remainder of the string. By storing the exact closing tag strings rather than recomputing them during each comparison, the code eliminates repeated string concatenation inside the main loop, reducing allocation overhead. Overall, the design balances readability with efficient single-pass parsing.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long string of letters and symbols is like a secret message wrapped in special envelopes. To see if the message is built correctly, the computer looks at it one piece at a time. It searches for tags that start with a little arrow pointing left and end with one pointing right. Think of these tags like opening and closing doors in a house. When it finds a tag that starts with a name, it adds that name to a pile to remember which door needs to be shut later. If it sees a special code for a comment, it ignores everything inside until it sees the end of that secret section. Every time it finds a tag that closes, it checks if it matches the very last door that was opened. If the computer finds a door that stays open or a door that closes at the wrong time, it knows the message is broken. By the time it finishes looking at the whole message, every door that was opened must be shut tidy and square. If everything is balanced and matches up, the message is perfect.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 5.93 | σ = 1.63

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Rust Python Java Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
JoshCrozier JS
keineahnung2345 C++
linouk23 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 Python
lzl124631x C++
ruoru Rust
suxrobGM C#
wisdompeak C++
28 links | 15 authors | 8 languages

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   July 10, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality