Skip to the code
cf.
+25 XP

#703 Breadcrumb to an Element

medium

Browser dev tools show a breadcrumb like body > main > ul > li for the selected element.

Write breadcrumb(root, targetId) that returns the list of tags from root down to the element whose id is targetId, both included. If no element has that id, or root is null, return an empty array. Elements have tag, id, and optional children.

Example 1

Input: root = {"tag":"body","id":"root","children":[{"tag":"header","id":"top","children":[{"tag":"h1","id":"title"}]},{"tag":"main","id":"content","children":[{"tag":"p","id":"intro"},{"tag":"ul","id":"list","children":[{"tag":"li","id":"a"},{"tag":"li","id":"b"}]}]}]}, targetId = "b"
Output: ["body","main","ul","li"]

li#b sits inside ul, inside main, inside body.

Example 2

Input: root = {"tag":"body","id":"root","children":[{"tag":"header","id":"top","children":[{"tag":"h1","id":"title"}]},{"tag":"main","id":"content","children":[{"tag":"p","id":"intro"},{"tag":"ul","id":"list","children":[{"tag":"li","id":"a"},{"tag":"li","id":"b"}]}]}]}, targetId = "zzz"
Output: []

No element has that id.

Constraints

  • The tree has 0 to 10^4 elements.
  • ids are unique.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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