Approach
Depth-first search
For Time Needed to Inform All Employees, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 58 lines of Python from the credited upstream file time-needed-to-inform-all-employees.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def numOfMinutes(self, n, headID, manager, informTime):10 """11 :type n: int12 :type headID: int13 :type manager: List[int]14 :type informTime: List[int]15 :rtype: int16 """17 children = collections.defaultdict(list)18 for child, parent in enumerate(manager):19 if parent != -1:20 children[parent].append(child)21 22 result = 023 stk = [(headID, 0)]24 while stk:25 node, curr = stk.pop()26 curr += informTime[node]27 result = max(result, curr)28 if node not in children:29 continue30 for c in children[node]:31 stk.append((c, curr))32 return result33 34 35363738class Solution2(object):39 def numOfMinutes(self, n, headID, manager, informTime):40 """41 :type n: int42 :type headID: int43 :type manager: List[int]44 :type informTime: List[int]45 :rtype: int46 """47 def dfs(informTime, children, node):48 return (max(dfs(informTime, children, c)49 for c in children[node])50 if node in children51 else 0) + informTime[node]52 53 children = collections.defaultdict(list)54 for child, parent in enumerate(manager):55 if parent != -1:56 children[parent].append(child)57 return dfs(informTime, children, headID)58