Skip to content
Onsite

Given two identical DOM trees and a node in one, find the matching node in the other.

MediumP3Coding

Two DOM trees have identical structure. Given the root of each tree and a node inside the first tree, return the node at the same position in the second tree.

Implement findMatchingNode(rootA, rootB, target).

  • Nodes expose parentNode and a children list, like DOM elements.
  • target can be rootA itself, in which case the answer is rootB.
  • If target is not inside rootA, return null.
  • Do not search by tag, id or text: elements may repeat. Use the position only.

Example 1

Input
rootA: div > [p, ul > [li, li]]; target = the second li of rootA
Output
the second li of rootB
Why
The path from the root is child 1 (ul), then child 1 (the second li).

Constraints

  • The trees have the same shape.
  • Depth up to 10^4, so avoid recursion that could overflow the stack.

Hints

Run checks the 3 visible tests, Submit all 6.