Leetcode 690. Employee Importance
You have a data structure representing a company of employees. Each employee has a unique ID, a value representing their importance, and a list of IDs of their direct subordinates. You need to find the total importance value of an employee and all their subordinates.
Example:
Employee info:
[
{ "id": 1, "importance": 5, "subordinates": [2, 3] },
{ "id": 2, "importance": 3, "subordinates": [] },
{ "id": 3, "importance": 3, "subordinates": [] }
]
Given the employee ID 1, the total importance value should be 11.
Note:
Employee
class is predefined. Here it is for reference:class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
}
Employee
object for quick access.Here is the Java implementation of the described approach:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
}
public class Solution {
private Map<Integer, Employee> employeeMap;
public int getImportance(List<Employee> employees, int id) {
// Create a map from id to Employee object for fast access
employeeMap = new HashMap<>();
for (Employee emp : employees) {
employeeMap.put(emp.id, emp);
}
return dfs(id);
}
private int dfs(int id) {
Employee emp = employeeMap.get(id);
int totalImportance = emp.importance;
for (int subId : emp.subordinates) {
totalImportance += dfs(subId);
}
return totalImportance;
}
}
Time Complexity: The DFS approach ensures that each employee and each subordinate relationship is visited exactly once. Given n
total employees, the time complexity is O(n)
.
Space Complexity: The space complexity is also O(n)
due to the storage required for the hashmap and the system stack during recursive calls.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?