Skip to the solution
HardFrontendAsked in 20246 min read

Find nearest common ancestor node

3.1k views

The problem

Problem, as an interviewer would state it: "Given two DOM nodes, find their NEAREST COMMON ANCESTOR — the deepest single node that is an ancestor of (or equal to) BOTH given nodes."

Examples:

Code
findNearestCommonAncestor(nodeC, nodeE); // returns their shared ancestor, e.g. #root

Clarifying questions expected:

  • If one node is itself an ancestor of the other, is the answer that ancestor node itself?
  • If the same node is passed for both arguments, is the answer that node itself?
  • Can this assume the two nodes are genuinely in the SAME document tree, or must it handle the case where they are not?

Code / implementation expected: Yes — real, direct proof against a real jsdom tree, covering both a straightforward two-leaves case and the ancestor/self edge cases.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the nearest-common-ancestor finder produces the correct real DOM element across 4 scenarios in a real jsdom tree

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 131 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Efficiently Merge Two Sparse Arrays (With Holes) Without Iterating Every Index

Continue