Dsa
Binary Search Tree
Medium
LCA Distance Sum
Build a BST from a sequence. You are given several pairs of nodes. For each pair, find their Lowest Common Ancestor (LCA) and calculate its distance from the root (where root distance = 0). Output the sum of these distances for all pairs.
Input Format:
- Line 1: Space-separated integers to build the BST.
- Line 2: An integer M (number of pairs).
- Next M lines: Two integers X and Y.
Output Format:
- A single integer representing the sum of LCA distances.
Example:
Input:
10 5 15 2 7 12 18
2
2 7
2 12
Output:
1
Explanation: LCA(2,7) is 5. Distance of 5 from root (10) is 1. LCA(2,12) is 10. Distance of 10 from root is 0. Sum = 1 + 0 = 1.
Key concepts
binary_search_treelowest_common_ancestorpath_finding
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now