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.
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.
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.
1 to 10^4 elements.ids are unique, and both firstId and secondId are in the tree.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).
I'm here to help with #704 Nearest Shared Container. 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.