#690
Employee Importance
MediumArrayHash TableTreeDepth-First SearchBreadth-First SearchHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a depth-first search (DFS) approach with a hash map to store employee data. This allows us to efficiently access each employee's information and calculate the total importance without redundant searches.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store employees by their ID for O(1) access.
- 2Step 2: Define a recursive function that takes an employee ID and calculates their total importance by summing their importance and the importance of their subordinates.
- 3Step 3: Call the recursive function with the given employee ID and return the result.
solution.py15 lines
1class Employee:
2 def __init__(self, id, importance, subordinates):
3 self.id = id
4 self.importance = importance
5 self.subordinates = subordinates
6
7def getImportance(employees, id):
8 employee_map = {e.id: e for e in employees}
9 def dfs(emp_id):
10 emp = employee_map[emp_id]
11 total = emp.importance
12 for sub_id in emp.subordinates:
13 total += dfs(sub_id)
14 return total
15 return dfs(id)ℹ
Complexity note: The time complexity is O(n) because we visit each employee exactly once. The space complexity is also O(n) due to the hash map storing employee data.
- 1Using a hash map allows for faster lookups of employee data, which is crucial for optimizing the solution.
- 2Recursive approaches can simplify the logic of traversing hierarchical data structures like employee subordinates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.