Skip to the code
cf.
+25 XP

#344 Common Ancestor in the DOM

medium

A text-highlighting tool needs the smallest element that contains both ends of a selection. The page is given as nested JSON: each element is { "id": ..., "children": [...] }, and children may be missing or empty. Ids are unique strings.

Write commonAncestor(dom, a, b) that returns the id of the deepest element that contains both the element with id a and the element with id b. An element contains itself, so if one element is inside the other, the answer is the outer one. Both ids always exist.

Example 1

Input: dom = {"id":"body","children":[{"id":"nav","children":[{"id":"logo"},{"id":"menu"}]},{"id":"main","children":[{"id":"post"}]}]}, a = "logo", b = "menu"
Output: "nav"

logo and menu are both children of nav.

Example 2

Input: dom = {"id":"body","children":[{"id":"nav","children":[{"id":"logo"},{"id":"menu"}]},{"id":"main","children":[{"id":"post"}]}]}, a = "menu", b = "post"
Output: "body"

menu is inside nav and post is inside main; only body holds both.

Constraints

  • 1 <= number of elements <= 10^4
  • 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).