Sponsored
Sponsored
The problem can be approached by using a Depth-First Search (DFS). The main idea is to accumulate the importance of an employee and all of their direct and indirect subordinates. We use a recursive function to traverse the subordinates of each employee. The base case is when an employee has no subordinates (leaf node). Each recursion step accumulates importance from the current employee and proceeds to accumulate from its subordinates.
Time Complexity: O(N), where N is the number of employees, as each employee is visited once.
Space Complexity: O(N), due to the recursion stack and storage in the map for employees.
1function getImportance(employees, id) {
2 const employeeMap = new Map();
3 for (const e of employees) {
4 employeeMap.set(e.id, e);
5 }
6
7 function dfs(empId) {
8 const employee = employeeMap.get(empId);
9 let totalImportance = employee.importance;
10 for (const subId of employee.subordinates) {
11 totalImportance += dfs(subId);
12 }
13 return totalImportance;
14 }
15
16 return dfs(id);
17}
In this JavaScript solution, a map is used for constant time employee lookups, and a helper dfs
function accumulates importance value recursively for the employee and their subordinates.
An alternative method involves using Breadth-First Search (BFS). In this approach, a queue is used to iteratively explore each level of employee hierarchy starting from the given employee ID. One processes each employee by summing their importance and enqueuing their subordinates. This technique assures visiting all employees in a breadth-wise manner and eventually collecting the cumulative importance value.
Time Complexity: O(N), as it processes each employee once.
Space Complexity: O(N), due to the queue and employee mapping storage.
1import
In this Java version, BFS is utilized using a queue structure. The code follows a similar pattern of summing the importance of dequeued employees and adding their subordinates into the queue.