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.
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.
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.
1 <= number of elements <= 10^43000 levels deep.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).
I'm here to help with #344 Common Ancestor in the DOM. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.