easyTreesGoogleAmazonMicrosoftFacebook
Common Distribution Grid
An electrical utility layout maps power hubs in sorted voltage values. To find the closest mutual hub for two houses, engineers calculate the Lowest Common Ancestor.
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes `p` and `q` in the BST.
Choose approach
6
curr
2
p
8
q
0
4
7
9
3
5
1/2
Narrationstep 1 of 2
Evaluate node 6. Targets are 2 and 8.
Variables
curr=6
p=2
q=8
How to think about it
- Start at the root.
- If both target node values are greater than root, move to the right child.
- If both target node values are less than root, move to the left child.
- The first node that does not satisfy both (where values break directions) is the LCA.
Edge cases to catch in interview
- One target node is the parent of another -> node itself is the LCA.
- Small tree with only root and children -> root is LCA.
Examples
Example 1
6{"arr":[6,2,8,0,4,7,9,null,null,3,5],"pVal":2,"qVal":8}
Example 2
2{"arr":[6,2,8,0,4,7,9,null,null,3,5],"pVal":2,"qVal":4}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed