Python 1376.py
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
sub = defaultdict(list)
for i, m in enumerate(manager):
sub[m].append(i)
def deeper(id):
if id not in sub:
return 0
slowest = 0
for s in sub[id]:
slowest = max(slowest, deeper(s))
return slowest + informTime[id]
return deeper(headID)
Difficulty
and has an acceptance rate of about 61% (400k+ submissions).
Typical patterns to solve this problem:
- Breadth First Search
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of determining the total time needed for an information cascade to reach all employees in a hierarchical organization. The hierarchy is described by a manager array where each employee’s direct manager is identified, and an informTime array that specifies how long each manager takes to inform their direct reports. Starting from the head of the organization, the algorithm computes the longest path of cumulative inform times, which corresponds to the overall time required for the message to propagate to every employee.
Construction of the Subordinate Mapping
The first logical block builds a reverse adjacency list that maps each manager to the list of their direct subordinates. This transformation is essential because the original manager array provides a parent-to-child relationship only implicitly. By iterating over the manager array with enumerate, the code captures both the employee index (i) and the manager identifier (m). For each pair, the employee is appended to the manager’s list in a defaultdict(list) structure.
sub = defaultdict(list)
for i, m in enumerate(manager):
sub[m].append(i)
This mapping enables constant-time access to any manager’s direct reports during the recursive traversal.
Recursive Depth-First Traversal
The core of the solution is the nested function deeper, which performs a depth-first search (DFS) starting from a given employee identifier. The function first checks whether the current identifier appears as a key in the subordinate mapping. If the identifier is absent, the employee has no direct reports, and the function returns 0, indicating that no additional time is needed beyond the current point.
def deeper(id):
if id not in sub:
return 0
When subordinates exist, the function iterates over each direct report, recursively invoking deeper to compute the time required for the subtree rooted at that subordinate. The variable slowest tracks the maximum time among all subtrees, reflecting the fact that the overall propagation time is dictated by the longest branch. After processing all children, the function adds the current manager’s informTime to the maximum child time and returns the result.
slowest = 0
for s in sub[id]:
slowest = max(slowest, deeper(s))
return slowest + informTime[id]
The final result is obtained by invoking deeper with the headID, which represents the root of the hierarchy.
return deeper(headID)
Edge Cases Handled
The algorithm gracefully handles several edge conditions without requiring explicit checks outside the main logic.
When the organization consists of a single employee who is also the head, the manager array contains -1 for the head, and the subordinate mapping will have no entry for the head. The deeper function immediately returns 0, correctly indicating that no propagation time is needed.
If an employee’s informTime is 0, the recursion still proceeds correctly because the addition of informTime[id] does not alter the accumulated time. This situation arises when a manager can inform subordinates instantaneously, and the algorithm naturally incorporates such cases.
The code also accommodates sparse hierarchies where some managers have only one direct report while others have many. The use of max ensures that the longest chain determines the final result, regardless of the branching factor at any level.
When the manager array contains -1 entries for employees other than the head (which would be invalid input), the construction of the subordinate mapping would place those employees under the key -1. Since the recursive call starts from headID, any unrelated components are never traversed, effectively isolating the valid hierarchy. This behavior demonstrates robustness against malformed but non-disruptive inputs.
Performance Optimizations
The solution leverages a few implicit optimizations that contribute to its efficiency.
The subordinate mapping is built using a defaultdict(list), which eliminates the need for explicit existence checks before appending a subordinate. This reduces overhead during the construction phase and keeps the code concise.
The recursive DFS visits each employee exactly once. By returning the computed time for each subtree and reusing that value only within the current call stack, the algorithm avoids redundant calculations. The use of a local variable slowest to retain the maximum child time ensures that only a single pass over the children is required, rather than multiple passes or auxiliary data structures.
Tail recursion is not employed, but the recursion depth is bounded by the height of the hierarchy, which in the worst case equals the number of employees. Python’s recursion limit is typically sufficient for the problem constraints, and the straightforward recursion avoids the overhead of managing an explicit stack.
The final return statement directly invokes the recursive helper with the head identifier, eliminating any unnecessary post-processing steps. This direct approach ensures that the result is produced as soon as the traversal completes.
Overall, the code combines a clear transformation of input data with a concise recursive strategy, resulting in a solution that is both readable and performant for the intended problem domain.
ELI5 - Simplified Explanation
Imagine a big company where everyone is connected like branches on a tree. At the very top, there is one person who knows a piece of important news. That person needs to tell their team members, who then go tell their own team members, until everyone knows the news.
Think of the company as a group of friends holding hands in a line. The person at the top has a list of people they are directly in charge of. To organize this, the computer creates a map that connects every manager to the people working under them.
To figure out how long it takes for the news to reach the last person, the computer starts at the top with the person who has the news. It looks at everyone that person manages and starts a little game of follow the leader.
The computer explores each path down the branches to see how long it takes for the message to travel. If one person has many people to whisper to, the computer waits for all of them to finish their jobs. It keeps track of the time spent at each step, making sure to pick the longest path because the company cannot move faster than the person who takes the most time.
The computer keeps digging deeper and deeper through the branches until it reaches the people who are not managers themselves. Once it reaches the bottom of a branch, it adds up all the time spent passing the message along that specific path. By checking every path, the computer finds the total time needed for the message to flow from the very top to the very last leaf on the tree.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Python | C# | Go | TS | ||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| martianoff | Scala | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| MacJim | C++ | |||||||||
| martianoff | Scala | |||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 104: Maximum Depth of Binary Tree
- problem 124: Binary Tree Maximum Path Sum
Solved On The Same Day
- problem 997: Find the Town Judge
- problem 695: Max Area of Island
- problem 797: All Paths From Source to Target
- problem 802: Find Eventual Safe States
- problem 863: All Nodes Distance K in Binary Tree
- problem 934: Shortest Bridge
- problem 1020: Number of Enclaves
- problem 1091: Shortest Path in Binary Matrix
- problem 1129: Shortest Path with Alternating Colors
- problem 1306: Jump Game III
- problem 1557: Minimum Number of Vertices to Reach All Nodes
- problem 2038: Remove Colored Pieces if Both Neighbors are the Same Color
- problem 212: Word Search II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality