You are given a data structure of employee information, which includes the employee’s unique ID, their importance value, and their direct subordinates’ IDs. You need to implement a function to return the total importance value for a given employee and all their direct and indirect subordinates.
The employee structure is as follows:
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
The function signature is:
def getImportance(employees: List['Employee'], id: int) -> int:
To solve this problem, we can use either Depth-First Search (DFS) or Breadth-First Search (BFS) to traverse the employee hierarchy starting from the given employee ID.
Because we need to get the importance of an employee and all their subordinates, a map (dictionary) will be useful to quickly access each employee object by their ID.
Employee
instance.We will use DFS in this solution for its simplicity in recursive implementation.
Here’s the Python implementation of the strategy discussed:
from typing import List
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
def getImportance(employees: List[Employee], id: int) -> int:
# Create a dictionary to map employee id to Employee object
employee_map = {employee.id: employee for employee in employees}
def dfs(employee_id: int) -> int:
employee = employee_map[employee_id]
total_importance = employee.importance
for sub_id in employee.subordinates:
total_importance += dfs(sub_id)
return total_importance
return dfs(id)
The time complexity of this solution is (O(N)), where (N) is the number of employees. This is because in the worst-case scenario, we might need to visit every employee once to sum up their importance. Each employee and their subordinates are visited exactly once.
The space complexity is also (O(N)) due to the recursion stack (DFS) which, in the worst-case scenario, can be as deep as the number of employees. The dictionary mapping will also use (O(N)) space to store employee mappings.
This implementation ensures that we efficiently compute the total importance by leveraging a map for quick lookups and DFS for hierarchy traversal.
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?