Skip to the code
+50 XP

#365 Parse a Compact DOM Snapshot

hard

A testing tool stores DOM snapshots in a compact text form. An element is its tag name, optionally followed by its children in parentheses, separated by commas. For example div(h1,ul(li,li)) is a div holding an h1 and a ul, and the ul holds two lis. Tag names use lowercase letters and digits; there are no spaces.

Write parseSnapshot(text) that returns the root element as nested objects { "tag": ..., "children": [...] }. Elements without parentheses have children: []. Parentheses are never empty, and the text is always valid.

Example 1

Input: text = "div(h1,ul(li,li))"
Output: {"tag":"div","children":[{"tag":"h1","children":[]},{"tag":"ul","children":[{"tag":"li","children":[]},{"tag":"li","children":[]}]}]}

h1 has no parentheses, so it has no children; ul has two.

Example 2

Input: text = "p"
Output: {"tag":"p","children":[]}

A single element with no children.

Constraints

  • 1 <= text.length <= 10^6
  • Elements are nested at most 500 levels deep.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).