You have a data structure of employee information, including the employee’s unique ID, importance value, and direct subordinates’ IDs.
You are given an array of employees employees where:
employees[i].id is the ID of the ith employee.
employees[i].importance is the importance value of the ith employee.
employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.
Given an integer id that represents an employee’s ID, return thetotal importance value of this employee and all their direct and indirect subordinates.

Input: employees =[[1,5,[2,3]],[2,3,[]],[3,3,[]]], id =1Output: 11Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.They both have an importance value of 3.Thus, the total importance value of employee 1is5+3+3=11.

Input: employees =[[1,2,[5]],[5,-3,[]]], id =5Output: -3Explanation: Employee 5 has an importance value of -3 and has no direct subordinates.Thus, the total importance value of employee 5is-3.
The total importance for an employee is the sum of their own importance and the importance of all their direct and indirect subordinates. This is naturally solved by traversing the employee hierarchy recursively.
classSolution {
publicintgetImportance(List<Employee> employees, int id) {
Map<Integer, Employee> mp =new HashMap<>();
for (Employee e : employees) mp.put(e.id, e);
return dfs(id, mp);
}
privateintdfs(int id, Map<Integer, Employee> mp) {
Employee e = mp.get(id);
int ans = e.importance;
for (int sub : e.subordinates) ans += dfs(sub, mp);
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dataclassEmployee(
val id: Int,
val importance: Int,
val subordinates: List<Int>
)
classSolution {
fungetImportance(employees: List<Employee>, id: Int): Int {
val mp = employees.associateBy { it.id }
fundfs(i: Int): Int {
val e = mp[i]!!var ans = e.importance
for (sub in e.subordinates) ans += dfs(sub)
return ans
}
return dfs(id)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classEmployee:
def__init__(self, id: int, importance: int, subordinates: list[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
classSolution:
defgetImportance(self, employees: list[Employee], id: int) -> int:
mp = {e.id: e for e in employees}
defdfs(i: int) -> int:
e = mp[i]
ans = e.importance
for sub in e.subordinates:
ans += dfs(sub)
return ans
return dfs(id)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashMap;
impl Solution {
pubfnget_importance(employees: Vec<Employee>, id: i32) -> i32 {
let mp: HashMap<i32, &Employee>= employees.iter().map(|e| (e.id, e)).collect();
fndfs(i: i32, mp: &HashMap<i32, &Employee>) -> i32 {
let e = mp[&i];
letmut ans = e.importance;
for&sub in&e.subordinates {
ans += dfs(sub, mp);
}
ans
}
dfs(id, &mp)
}
}