Tag Validator

Hard · Stack & Strings · String · Stack

Problem

You are given a string code containing a code snippet. Return true if the snippet is valid and false otherwise. A snippet is valid when all of these rules hold:

Examples

Input: code = "<B><![CDATA[</B>]]>ok</B>"
Output: true

The inside the CDATA section is ignored, so the outer B closes at the end.

Input: code = "<A></A><B></B>"
Output: false

The snippet is two sibling tags rather than one wrapping tag.

Input: code = "<AB>x</ab>"
Output: false

The end tag name is lowercase and does not match AB.

Constraints

Approaches

Follow-up

The order of the checks matters: <![CDATA[ and </ both start with <, so they must be tested before the start-tag case. The use cases reuse the same scan to report how deeply the tags nest and how many there are.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…