Skip to the code
+25 XP

#704 Nearest Shared Container

medium

A rich-text editor needs the smallest element that contains both ends of the user's selection, so it can apply formatting to that element. This is what Range.commonAncestorContainer gives you in the browser.

Write sharedContainer(root, firstId, secondId) that returns the id of the deepest element that contains both elements. An element contains itself, so if one element is inside the other, the outer one is the answer. Both ids exist in the tree. 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"}]}]}]}, firstId = "intro", secondId = "b"
Output: "content"

p#intro and li#b are both inside main#content, and no deeper element holds both.

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"}]}]}]}, firstId = "list", secondId = "a"
Output: "list"

li#a is inside ul#list, so the list itself is the answer.

Constraints

  • The tree has 1 to 10^4 elements.
  • ids are unique, and both firstId and secondId are in the tree.
  • Elements are nested at most 3000 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).