A file manager keeps every folder as an object that points to its parent folder. To show "moving a to b crosses N folders" or to find the folder that contains both of two selected files, it needs their lowest common ancestor: the deepest node that is an ancestor of both. A node counts as its own ancestor.
Nodes are plain objects with at least { value, parent }. parent is the parent node, or null for a root. Nodes may have other fields (such as children), but you only need parent, and you are not given the root. Values may repeat; nodes are compared by identity.
Write two functions:
lowestCommonAncestor(a, b) returns the lowest common ancestor node of a and b, or null if they are in different trees.
distanceBetween(a, b) returns the number of edges on the path from a to b through that ancestor, or -1 if they are in different trees.
Rules:
If a === b, the answer is a and the distance is 0. If one node is an ancestor of the other, the ancestor is the answer.
Throw a TypeError if a or b is not an object.
Use O(1) extra space: no sets or arrays of ancestors. Trees can be 200,000 levels deep, and comparing every ancestor of a with every ancestor of b is far too slow.
// root// / \// docs src// / \ \// work photos app// |// taxeslowestCommonAncestor(taxes, photos); // docslowestCommonAncestor(taxes, app); // rootlowestCommonAncestor(docs, taxes); // docs (a node is its own ancestor)distanceBetween(taxes, photos); // 3: taxes → work → docs → photosdistanceBetween(taxes, otherTreeNode); // -1
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
6
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.