progress

~/problems / Stacks / Stack: path parsing

Where each piece of text lives

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A tiny markup has <name> to open and </name> to close an element (lowercase names); everything else is text. For each piece of text, find the elements around it.

Write text_paths(doc: str) -> list[tuple[str, str]] | None. Split the text between tags into runs, strip spaces, and skip empty ones. For each run output (path, text), where path joins the open elements outermost first with / ("" outside all). If tags don't nest properly (wrong closer, closer with nothing open, or left open), return None.

text_paths("<note><to>Ana</to><body>Hi <b>there</b> friend</body></note>")
# [("note/to", "Ana"), ("note/body", "Hi"), ("note/body/b", "there"), ("note/body", "friend")]

text_paths("intro <p>x</p>")   # [("", "intro"), ("p", "x")]
text_paths("<a><b>x</a></b>")  # None   (</a> arrives while <b> is innermost)
text_paths("<a>x")             # None   (<a> is never closed)
text_paths("")                 # []

len(doc) <= 10^6; < and > only appear in well-formed tags. Nesting goes thousands deep, so don't recurse. ⭐ Bonus: a speed test earns a star in O(len(doc)).

Show hint

at each <, find > with doc.find(">", i); push opening names and pop-and-compare on closers, flushing the text collected since the last tag.

Topic: Stack: path parsing. Resolve ., .. and symlinks with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc