VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-company-queries-ii/

⇱ CSES Solutions - Company Queries II - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Company Queries II

Last Updated : 23 Jul, 2025

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:

  • Run a Depth-First-Search to find the depth of all the nodes.
  • Fill the first column for every node i with the immediate boss of node i.
  • Fill the remaining columns with the formula: LCA[i][j] = LCA[LCA[i][j - 1]][j - 1].
  • To answer each query,
    • Find the difference in depth of both the nodes.
    • From the deeper node, use the LCA[][] table to make jumps in upward direction till both the nodes reach the same depth.
    • After reaching the same depth, make jumps from both nodes till their ancestors are different.
    • When the ancestor becomes same, return the ancestor node.

Below is the implementation of the algorithm:


Output
3
1
1

Time Complexity: O(nlogn + qlogn)
Auxiliary Space: O(nlogn)

Comment
Article Tags:
Article Tags: