![]() |
VOOZH | about |
A company has n employees, who form a tree hierarchy where each employee has a boss, except for the general director. Your task is to process q queries of the form: who is the lowest common boss of employees a and b in the hierarchy?
The employees are numbered 1,2,β¦,n, and employee 1 is the general director. The array arr[] has nβ1 integers e2β,e3β,β¦,enβ: for each employee 2,3,β¦,n their boss. Finally, there are q queries, each query has two integers a and b: who is the lowest common boss of employees a and b?
Examples:
Input: n = 5, q = 3, arr[] = {1, 1, 3, 3}, queries[][] = {{4, 5}, {2, 5}, {1, 4}}
Output:
3
1
1
Explanation:
- Lowest Common Boss of 4 and 5 is 3.
- Lowest Common Boss of 2 and 5 is 1.
- Lowest Common Boss of 1 and 4 is 1.
Input: n = 10, q = 3, arr[] = {1, 1, 1, 1, 2, 3, 4, 4, 1}, queries[][] = {{1, 8}, {2, 7}, {8, 3}}
Output:
1
1
1
Explanation:
- Lowest Common Boss of 1 and 8 is 1.
- Lowest Common Boss of 2 and 7 is 1.
- Lowest Common Boss of 8 and 3 is 1.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Binary Lifting Technique. We can construct the LCA table, such that LCA[i][j] stores the (2^j)th ancestor of node i. In order to fill the first column of LCA table, update the first column of each node i with immediate boss of node i. To fill the remaining columns, we can use the formula: LCA[i][j] = LCA[LCA[i][j - 1]][j - 1]. After filling the LCA[][] table completely, we can answer each query in logN time using Binary Lifting.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3 1 1
Time Complexity: O(nlogn + qlogn)
Auxiliary Space: O(nlogn)