Time Needed to Inform All Employees — LeetCode 1376 Python Solution
MediumTreeDepth-First SearchBreadth-First Search
- Problem
- #1376
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.
Example
- Input
- n = 1, headID = 0, manager = [-1], informTime = [0]
- Output
- 0
- Explanation
- The head of the company is the only employee in the company.
Python solution
Python
class Solution:
def numOfMinutes(
self, n: int, headID: int, manager: List[int], informTime: List[int]
) -> int:
def dfs(i: int) -> int:
ans = 0
for j in g[i]:
ans = max(ans, dfs(j) + informTime[i])
return ans
g = defaultdict(list)
for i, x in enumerate(manager):
g[x].append(i)
return dfs(headID)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1376. Time Needed to Inform All Employees is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1376. Time Needed to Inform All Employees?
- LeetCode 1376. Time Needed to Inform All Employees is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1376. Time Needed to Inform All Employees?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1376. Time Needed to Inform All Employees?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1376. Time Needed to Inform All Employees cover?
- LeetCode 1376. Time Needed to Inform All Employees is tagged Tree, Depth-First Search and Breadth-First Search on LeetCode.