FrontendInterviews.dev

Loading problem…

329. Find Corresponding Node in Two Identical DOM Trees

Easy•

Given two structurally identical DOM trees (rootA and rootB) and a target element located somewhere inside tree A, find and return the exact corresponding DOM node in tree B.

In real-world usage, this problem maps directly to "virtual DOM" diffing scenarios: if you know a node changed in the previous tree representation, you must locate the exact same node position in the new tree to execute pinpoint UI updates.

Requirements

Implement the findCorrespondingNode function:

function findCorrespondingNode(rootA, rootB, target) {}

Core Mechanics

  • The function must locate the node in rootB that shares the exact same relative structural path from the root as target shares with rootA.
  • Identity Restriction: You are forbidden from using selectors, IDs, classes, or textual content to match nodes. Structural positioning (like child index paths) is the *only* guarantee of identity.

Edge Cases

  • If target is identical to rootA, the answer is obviously rootB.
  • If either root or the target are null, immediately return null.
  • If target does not belong anywhere within the rootA sub-tree (an "outsider" node), safely return null instead of throwing an error or looping infinitely.

Example Usage

// Tree A: <div><p>Sibling</p><span>Target</span></div>
// Tree B: <div><p>Sibling</p><span>Twin</span></div>

const rootA = document.getElementById('a');
const rootB = document.getElementById('b');
const target = rootA.children[1]; // The <span>

const twin = findCorrespondingNode(rootA, rootB, target);
// Result: The <span> element inside Tree B

Constraints

  • Use tree position, not element attributes/content.
  • Return null for invalid roots or out-of-tree target.
  • Handle duplicate tags and duplicate text values correctly.
  • Target is an Element (not Text/Comment node).
Accepted5/11|Acceptance Rate45.5%