⚡Flashcard Drill➔
NeetCode #440LC-1376MediumTrees
← Back to All Problems

#440 · #1376 · Time Needed to Inform All Employees(通知所有员工所需的时间)

📌 Problem Statement & Constraints

A company has n employees with a unique head, given by headID and the manager array. Each manager takes informTime[i] minutes to inform their direct reports, who then inform theirs in parallel. Return the total minutes needed to inform all employees. Constraints: 1 <= n <= 10^5, 0 <= headID < n; the manager relation forms a tree.

💡 Core Algorithmic Approaches

  1. The structure is a tree rooted at headID, with edges from manager to report.
  2. The time for a node's subtree is informTime[node] + max(time of each child's subtree), since the children are informed in parallel.
  3. So a post-order DFS returning the subtree time gives the answer at the root.
  4. The manager array must be inverted into a children adjacency list first.

💻 Benchmark Python3 Implementation

class Solution:
    def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
        from collections import defaultdict
        children = defaultdict(list)
        for i, m in enumerate(manager):
            if m != -1:
                children[m].append(i)      # invert manager -> reports

        def dfs(node: int) -> int:
            if not children[node]:
                return 0                   # a leaf takes no time to inform others
            # children are informed in parallel -> take the maximum
            return informTime[node] + max(dfs(c) for c in children[node])

        return dfs(headID)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(n) for the adjacency list plus O(h) for the recursion.

⚠️ Interview Pitfalls & Follow-ups

  • Summing the children's times instead of taking the maximum: the informing happens in parallel, so the longest branch determines the total.
  • Forgetting the leaf case: a leaf returns 0, not informTime[leaf] (which is 0 anyway, but the guard makes it explicit).
  • Building the adjacency list in the wrong direction: the edges go from manager to report.
  • Handling the head's manager being -1: the if m != -1 guard is required.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Trees Problems

中文速览与面试要点

通知所有员工所需的时间

公司里有 n 名员工,每个员工的 ID 都是独一无二的,编号从 0 到 n − 1。公司的总负责人通过 headID 进行标识。在 manager 数组中,每个员工都有一个直属负责人,其中 manager[i] 是第 i 名员工的直属负责人。对于总负责人, manager[headID] = -1 。题目保证从属关系可以用树结构表示。公司总负责人想要向公司所有员工通知一条紧急消息。他将会通知他的所有直属下属,这些下属将继续通知他们的直属下属,以此类推直到所有员工都被通知到。第 i 名员工需要 informTime[i] 分钟来通知他的所有直属下属(也就是说在 informTime[i] 分钟后,他的所有直属下属都可以开始传播这一消息)。返回通知所有员工所需的时间。约束:1 ≤ n ≤ 10^5;0 ≤ headID &lt; n;manager.length == n;0 ≤ manager[i] &lt; n;manager[headID] == -1;informTime.length == n;0 ≤ informTime[i] ≤ 1000;informTime[i] == 0 表示员工 i 不是负责人;题目保证所有员工都可以收到通知。

核心要点

  • 建树 + DFS 求最长路径(标准解) :用 manager 数组建出「负责人 → 直属下属」的邻接表,然后从 headID 做 DFS,返回「通知该子树所需的时间」= informTime[node] + max(子节点所需时间) 。
  • 为什么取 max 而非 sum :下属是 并行 接收通知的,因此耗时取决于最慢的那条链路。
  • 叶节点 : informTime 为 0,直接返回 0。
  • 复杂度 :O(n) 时间、O(n) 空间(邻接表 + 递归栈)。

常见陷阱

  • 把下属的耗时相加 :下属是并行接收的,必须取 max 而非 sum。
  • 忘记加上 informTime[node] :节点自身的通知耗时必须计入。
  • 从每个员工分别计算路径长度 :O(n²)。一次 DFS 即可。
  • 递归深度过大 :n 可达 10^5,链状结构会栈溢出。

参考实现

from collections import defaultdict

class Solution:
    def numOfMinutes(self, n: int, headID: int, manager: list[int],
                     informTime: list[int]) -> int:
        children = defaultdict(list)
        for i, m in enumerate(manager):
            if m != -1:
                children[m].append(i)       # 建「负责人 -> 下属」的邻接表

        def dfs(node: int) -> int:
            """返回从 node 开始通知其整棵子树所需的时间。"""
            t = 0
            for c in children[node]:
                ct = dfs(c)
                if ct > t:
                    t = ct                  # 取最慢的下属链路
            return t + informTime[node]

        return dfs(headID)