Given a map containing employee to manager mappings, find all employees under each manager who directly or indirectly reports him.

For example, consider the following employee-manager pairs:

A —> A
B —> A
C —> B
D —> B
E —> D
F —> E

Here, A reports to himself, i.e., A is head of the company and is the manager of employee B. B is the manager of employees C and D, D is the manager of employee E, E is the manager of employee F, C, and F is not managers of any employee.

Output:
 
A —> [B, D, C, E, F]
B —> [D, C, E, F]
C —> []
D —> [E, F]
E —> [F]
F —> []

Practice this problem

The idea is to construct a reverse map containing manager to employee mappings and recursively find all reporting employees (direct and indirect) in every manager’s hierarchy. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

A —> [C, D, F, B, E]
E —> [F]
F —> []
D —> [F, E]
C —> []
B —> [E, F, D, C]

Java


Download  Run Code

Output:

A —> [B, C, D, E, F]
B —> [C, D, E, F]
C —> []
D —> [E, F]
E —> [F]
F —> []

Python


Download  Run Code

Output:

C —> set()
F —> set()
E —> {‘F’}
D —> {‘F’, ‘E’}
B —> {‘C’, ‘F’, ‘E’, ‘D’}
A —> {‘C’, ‘D’, ‘B’, ‘F’, ‘E’}