Given one line of simplified HTML, print YES if every element is closed in the correct (nested) order, otherwise NO.
Rules:
- A tag is everything from
<to the next>. Text between tags never contains<or>, and neither do attribute values. <name ...>opens an element and</name>closes it. Tag names are made of letters and digits and are case-insensitive.- Tags starting with
<!(comments, doctype) are ignored. - A tag whose content ends with
/(like<br/>or<x-icon/>) closes itself. - Void elements never need closing:
area base br col embed hr img input link meta source track wbr. A closing tag for a void element (such as</br>) makes the document invalid.
Constraints
- The line is at most 20000 characters.
Input and output
- Input
- One line of HTML.
- Output
- `YES` or `NO`
Examples
Input 1
<div class="card"><p>Fees<br>₹5,000</p><img src="c.png" alt="campus"></div>Output
YESbr and img are void elements and need no closing tag.
Input 2
<ul><li>One</ul></li>Output
NOThe tags close in the wrong order.
Show hints
- This is the balanced-brackets problem with tag names as the brackets.
- Decide what to do with void, self-closing and comment tags before touching the stack.
Show the explanation
Extract tags with a regex such as /<([^>]*)>/g, and classify each one:
- Content starting with
!→ ignore. - Starting with
/→ a closing tag. If its name is void, answerNO. Otherwise the top of the stack must be the same name (compare in lower case); pop it, or answerNOif the stack is empty or holds a different name. - Ending with
/, or a void name → nothing to do. - Otherwise → push the lower-cased name.
At the end the stack must be empty (no unclosed elements).
Real browsers are far more forgiving: their parser auto-closes many elements (an unclosed <p> or <li>), which is why validators, linters and JSX compilers are stricter than the browser.
Original UniCircle question. Last reviewed 22 Oct 2026.
