#1376
Time Needed to Inform All Employees
MediumTreeDepth-First SearchBreadth-First SearchTree TraversalDepth-First SearchBreadth-First Search
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)
In the optimal approach, we can use a depth-first search (DFS) or breadth-first search (BFS) to traverse the tree structure of employees. We will calculate the total time needed to inform all employees by keeping track of the maximum time taken by any subordinate.
⚙️
Algorithm
3 steps- 1Step 1: Create an adjacency list to represent the tree structure of employees.
- 2Step 2: Use DFS or BFS to traverse the tree starting from the headID.
- 3Step 3: For each employee, calculate the total time as the inform time plus the maximum time from their subordinates.
solution.py14 lines
1# Full working Python code
2class Solution:
3 def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
4 from collections import defaultdict
5 tree = defaultdict(list)
6 for i in range(n):
7 if manager[i] != -1:
8 tree[manager[i]].append(i)
9 def dfs(emp):
10 max_time = 0
11 for sub in tree[emp]:
12 max_time = max(max_time, dfs(sub))
13 return max_time + informTime[emp]
14 return dfs(headID)ℹ
Complexity note: The time complexity is linear because we visit each employee exactly once. The space complexity is also linear due to the storage of the tree structure.
- 1Understanding tree structures is crucial for solving hierarchical problems.
- 2Recursion is a powerful tool for traversing trees.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.