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.
1using System.Collections.Generic;
class Employee {
public int id;
public int importance;
public IList<int> subordinates;
}
class Solution {
public int GetImportance(IList<Employee> employees, int id) {
var employeeMap = new Dictionary<int, Employee>();
foreach (var e in employees) {
employeeMap[e.id] = e;
}
var queue = new Queue<int>();
queue.Enqueue(id);
int totalImportance = 0;
while (queue.Count > 0) {
int currentId = queue.Dequeue();
var employee = employeeMap[currentId];
totalImportance += employee.importance;
foreach (var subId in employee.subordinates) {
queue.Enqueue(subId);
}
}
return totalImportance;
}
}
The C# solution employs a breadth-first traversal through a queue. As employees are dequeued, their importance is summed, and their subordinates are enqueued.