LCA - Lowest Common Ancestor
The lowest common ancestor (LCA) is a concept in graph theory and computer science.
Let ‘T’ be a rooted tree with ‘N’ nodes. The lowest common ancestor is defined between two nodes, ‘u’ and ‘v’, as the lowest node in ‘T’ that has both ‘u’ and ‘v’ as descendants (where we allow a node to be a descendant of itself). - Wikipedia
For the given tree, The LCA of nodes 5 and 8 will be node 2, as node 2 is the first node that lies in the path from node 5 to root node 1 and from node 8 to root node 1.
Path from node 5 to root node looks like 5 → 2 → 1.
Path from node 8 to root node looks like 8 → 6 → 2 → 1.
Since 2 is the first node that lies in both paths. Hence LCA will be 2.
Given any two nodes ‘u’ and ‘v’, find the LCA for the two nodes in the given Tree ‘T’.
Note: For each test case, the tree is rooted at node 1.
Input Format-
The first line contains an integer ‘T’ which denotes the number of test cases.
For each test case:
The first line contains a single integer ‘N’, denoting the number of nodes.
Each of the following ‘N’ - 1 line contains two space-separated integers, ‘ui’ and ‘vi’, which means an edge connects these two nodes.
The following line will contain a single integer ‘Q’, denoting the number of queries you have to answer for the given tree.
In the following ‘Q’ lines, each one will have two numbers, ‘u’ and ‘v’, for which you have to find the LCA of ‘u’ and ‘v’.
Output Format-
Your task is to print ‘Q’ lines for each test case.
The ‘Q’ lines should be the LCA of the given ‘u’ and ‘v’, respectively.
Constraints -
1<= ‘T' <= 5
1 <= ‘N’ <= 10^5
1 <= ‘Q’ <= 10^5.
1 <= ‘u’, ‘v’ <= ‘N’.
Time Limit: 1 sec
CodingNinjas
author
2y
I used the concept of recursion in trees and solved the probelm with O(n) complexity.
Search through the left and right subtrees and return answer.
The node which has one key present in its left subtre...read more
CodingNinjas
author
2y
Brute Force
Prerequisite - DFS
Approach:
We will store the depth and the direct parent of each node using a dfs.
Now, if we have to find the LCA to two nodes, first we would move upward the node which has...read more
CodingNinjas
author
2y
Binary Lifting
Prerequisite - Sparse Table, DFS
Approach:
Using Sparse Table, we can efficiently find the kth ancestor of any node in the tree in O(log(N)). Using this, we can divide the problem of findi...read more
Add answer anonymously...
Top Cvent Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app