All People Report to the Given Manager LeetCode Solution

Last updated on October 9th, 2024 at 10:12 pm

This Leetcode problem All People Report to the Given Manager LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

All People Report to the Given Manager LeetCode Solution

All People Report to the Given Manager LeetCode Solution

Problem Statement

Column NameType
employee_idint
employee_namevarchar
manager_idint
Table: Employees

employee_id is the primary key for this table.
Each row of this table indicates that the employee with ID employee_id and name employee_name reports his work to his/her direct manager with manager_id
The head of the company is the employee with employee_id = 1.

Write an SQL query to find employee_id of all employees that directly or indirectly report their work to the head of the company. The indirect relation between managers will not exceed 3 managers as the company is small. Return result table in any order without duplicates.

The result format is in the following example.

Example 1:
Input:

employee_id employee_namemanager_id
1Boss1
3Alice3
2Bob1
4Daniel2
7Luis4
8Jhon3
9Angela8
77Robert1
Employees table:

Output:

employee_id
2
77
4
7

Explanation:
The head of the company is the employee with employee_id 1.
The employees with employee_id 2 and 77 report their work directly to the head of the company.
The employee with employee_id 4 report his work indirectly to the head of the company 4 –> 2 –> 1.
The employee with employee_id 7 report his work indirectly to the head of the company 7 –> 4 –> 2 –> 1.
The employees with employee_id 3, 8 and 9 don’t report their work to head of company directly or indirectly.

1. All People Report to the Given Manager LeetCode Solution MySQL

select 
  distinct e1.employee_id 
from 
  Employees as e1 
  inner join Employees as e2 
  inner join Employees as e3 on e1.manager_id = e2.employee_id 
  and e2.manager_id = e3.employee_id 
where 
  e1.employee_id <> 1 
  and (
    e1.manager_id = 1 
    or e2.manager_id = 1 
    or e3.manager_id = 1
  );
Scroll to Top