Lowest Common Ancestor in an Explicit Binary Tree
OtherSoftware Engineer · Online AssessmentLast updated
Find the lowest common ancestor in a binary tree using explicit child arrays, including identical targets, ancestor targets, and deep trees.
The report identifies the LCA problem by name without a variant or representation. This executable practice version explicitly chooses an arbitrary binary tree with existing target nodes and the array representation below.
Implement lowest_common_ancestor(left, right, root, p, q) -> int:
left: int[]andright: int[]have the same lengthn.- Node IDs are the integers from
0throughn - 1.left[i]andright[i]identify nodei's children;-1means no child. root: intis the root node ID, andp: int,q: intare target node IDs.- Return the node ID of their lowest common ancestor.
Constraints & Assumptions
1 <= n <= 100000.- The arrays describe a valid rooted binary tree: all nodes are reachable from
root, there are no cycles, and every non-root node has exactly one parent. - Both targets exist and may be identical. IDs identify nodes; their numeric order has no relationship to tree position.
- The tree is not required to satisfy any binary-search-tree ordering.
- A target can be an ancestor of the other target. The tree may be a chain, so do not assume shallow recursion.
Examples
left = [1, -1, -1]
right = [2, -1, -1]
root = 0, p = 1, q = 2
result = 0
left = [1, 3, -1, -1, -1]
right = [2, 4, -1, -1, -1]
root = 0, p = 3, q = 4
result = 1
Hints
Hint 1
Locate where ancestry paths meet: The numeric IDs do not provide a search direction. Use the actual parent-child relationships, either by tracing ancestry or by combining information from subtrees.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.