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].idis the ID of theithemployee.employees[i].importanceis the importance value of theithemployee.employees[i].subordinatesis a list of the IDs of the direct subordinates of theithemployee.
Given an integer id that represents an employee’s ID, return the total importance value of this employee and all their direct and indirect subordinates.
solution
Pretty basic recursion/DFS. Use a hashmap for fast employee lookup.
def getImportance(self, employees: List['Employee'], id: int) -> int:
# construct hashmap for O(1) lookup
d = {}
for employee in employees:
d[employee.id] = employee
def dfs(eid):
res = d[eid].importance
for subordinate in d[eid].subordinates:
res += dfs(subordinate)
return res
return dfs(id)