Two trees with the same shape have the same paths: the target is "child 1 of child 0 of the root" in both. So start at the target and walk up with parentNode until you reach the first root, recording at each step which child you were. Then start at the second root and take the same steps down. That touches only the nodes on the path, O(depth × siblings), instead of searching the whole tree. The fallback when nodes have no parent pointer is to walk both trees together, depth first, and return the second tree's node when the first walk meets the target: correct, but O(n). Details that matter: use childNodes (not children) if the target can be a text node, and return null if the target isn't inside the first root.
Find the identical DOM node in two identical trees: given a node in one tree, locate the equivalent node in the other tree by reference. Efficient solution: walk up via parentNode, record the path, then replay the path in the other tree (avoids touching unrelated nodes vs. DFS/BFS).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
The recursion visits the same position in both trees at every step, so when it meets the target in the first tree it is holding the twin in the second. It needs no parent pointers, which makes it the answer for plain object trees. The cost is that it's a search: the checks show it reading the child list of every element that comes before a target late in the tree, and because it uses children it can't find a text node.
// Walk both trees together. When the walk reaches the target in tree A, the node at the same// position in tree B is its twin.function findTwin(rootA, rootB, target) {if (rootA === target) return rootB;for (let i = 0; i < rootA.children.length; i++) {const found = findTwin(rootA.children[i], rootB.children[i], target);if (found) return found;}return null;}
passes 5 checks run on every build, against the native method where there is one
- finds the same position in the other tree, by reference
- the root's twin is the other root
- a node that isn't in the first tree gives null
- the weakness: it reads every element on the way to a late target
- the weakness: text nodes aren't in `children`, so they are never found
From the target, each step up records the node's index among its parent's childNodes. Reaching rootA ends the climb; running out of parents first means the target was never inside it. Replaying the indexes from the last to the first walks down the second tree to the twin. For a node three levels down, three child lists are read in each tree and nothing else. childNodes includes text nodes, so text targets work and element indexes stay right when text sits between elements.
// Go up from the target to the root, noting at each step which child we were. Then replay// those steps downward in tree B. Only the nodes on the path are touched.function findTwin(rootA, rootB, target) {const path = [];let node = target;while (node !== rootA) {const parent = node.parentNode;if (!parent) return null; // reached the top without meeting rootA: target isn't inside itpath.push(Array.prototype.indexOf.call(parent.childNodes, node));node = parent;}let twin = rootB;for (let i = path.length - 1; i >= 0; i--) twin = twin.childNodes[path[i]];return twin;}
passes 6 checks run on every build, against the native method where there is one
- finds the same position in the other tree, by reference
- the root's twin is the other root
- a node that isn't in the first tree gives null
- touches only the path: three child lists in each tree for a node three levels down
- text nodes work, and count as children when indexing
- works on a subtree: the roots don't have to be the document
getPath and followPath are the two halves on their own. A path is an array of numbers, so it can be saved and resolved later: restoring a selection after a re-render, or naming a node to code that can't hold a reference to it. getPath counts previousSibling steps, so it never builds or searches a child list. followPath returns null when the tree has no node at that position, so trees that differ fail safely.
// The two halves as reusable functions. A path is plain data ([1, 0, 2]), so a node's position// can be stored, sent to another context, and resolved later.function getPath(root, node) {const path = [];for (let current = node; current !== root; current = current.parentNode) {if (!current.parentNode) return null; // node isn't inside rootlet index = 0;for (let s = current.previousSibling; s; s = s.previousSibling) index++; // no array, no searchpath.unshift(index);}return path;}// Null if the tree doesn't have that position (the two trees weren't identical after all).function followPath(root, path) {let node = root;for (const index of path) {node = node.childNodes[index];if (!node) return null;}return node;}function findTwin(rootA, rootB, target) {const path = getPath(rootA, target);return path && followPath(rootB, path);}
passes 8 checks run on every build, against the native method where there is one
- finds the same position in the other tree, by reference
- the root's twin is the other root
- a node that isn't in the first tree gives null
- getPath is the list of child indexes from the root down
- getPath reads no child lists at all
- followPath resolves a stored path
- trees that turn out to differ give null, not an exception
- text nodes and subtrees
Keeping a place across a re-render
When a subtree is replaced by an identical copy (a server-rendered fragment swapped in, a cloned template), the focused or selected node is found again by its path, since the old reference points into the removed tree.
parentNode, childNodes and children
childNodes holds every child including text and comments; children holds elements only. Index into the same one on both sides.
Hydration
Server rendering frameworks attach to existing markup by walking the rendered tree and the expected tree in step, the paired walk of the basic stage.
Searching the second tree by tag, class or text: many nodes can look the same; only the position identifies the twin.
Recording indexes in
childrenand replaying them inchildNodes(or the reverse).Replaying the path in the order it was recorded: it was collected bottom-up and must be followed top-down.
Looping forever, or throwing, when the target isn't inside the first root.
Calling
indexOfdirectly on aNodeList, which doesn't have it: useArray.prototype.indexOf.callor count siblings.
What's the complexity of each approach?
The paired walk is O(n) time in the worst case and O(depth) stack. The path approach is O(depth × b) where b is the number of siblings scanned for the index at each level, and O(depth) space for the path.
What if nodes have no parent pointer?
Then the paired walk is the only option, or build a Map from node to parent in one pass if many lookups will follow.
What if the trees aren't really identical?
Following the path can run off the tree. Check each step and return null, and if it matters compare nodeName along the way to detect a mismatch early.
Could you do it with built-in DOM APIs?
Two TreeWalkers advanced in step give the paired walk without recursion. There's no built-in for the path, though compareDocumentPosition and contains help check that the target is inside the root.