AlgoMaster Logo

Employee Importance

employees=[[1,5,[2,3]],[2,3,[]],[3,3,[]]],id=1
1class Employee {
2    public int id;
3    public int importance;
4    public List<Integer> subordinates;
5}
6
7class Solution {
8    public int getImportance(List<Employee> employees, int id) {
9        // Create a map to store each employee by their id
10        Map<Integer, Employee> map = new HashMap<>();
11
12        // Fill the map with the employee data
13        for (Employee emp : employees) {
14            map.put(emp.id, emp);
15        }
16
17        // Call the DFS helper function and return the total importance
18        return dfs(id, map);
19    }
20
21    // DFS function to compute the total importance starting from a particular employee id
22    private int dfs(int id, Map<Integer, Employee> map) {
23        // Get the current employee using the id
24        Employee employee = map.get(id);
25
26        // Start with the importance of the current employee
27        int totalImportance = employee.importance;
28
29        // Recursively get the importance of each subordinate
30        for (int subid : employee.subordinates) {
31            totalImportance += dfs(subid, map);
32        }
33
34        // Return the total computed importance
35        return totalImportance;
36    }
37}
0 / 17
1imp: 52imp: 33imp: 3Call Stack:(empty)Total Importance: 0Legend:Not visitedVisitingComputed