Skip to problem
←

Time Needed to Inform All Employees

Medium 0 attempts

The company's n employees are labeled 0 through n - 1. Employee headID is the head and knows the news at time 0.

manager[i] is employee i's direct manager; only the head has manager -1. The hierarchy is one rooted tree. After employee i receives the news, it takes informTime[i] minutes to inform all of their direct subordinates simultaneously. Each subordinate can then inform their own team independently.

Return the earliest time when every employee has received the news. Parallel branches do not add together: the answer is the longest accumulated delay from the head to an employee. Employees with no subordinates have an informing time of 0.

Function contract

Implement numOfMinutes(n, headID, manager, informTime).

Output: Return the earliest time, in minutes, at which every employee has received the news.

Example 1

Input
n = 6
headID = 2
manager = [2,2,-1,2,2,2]
informTime = [0,0,1,0,0,0]
Output
1

Explanation: The head informs all five direct subordinates in parallel, taking 1 minute in total, not 5 minutes.

Example 2

Input
n = 1
headID = 0
manager = [-1]
informTime = [0]
Output
0
Constraints
  • 1 <= n <= 10^5
  • 0 <= headID < n; manager[headID] == -1
  • Every other manager entry is in [0,n-1]; the hierarchy forms one rooted tree.
  • 0 <= informTime[i] <= 1000; employees with no subordinates have informTime[i] == 0.
  • manager.length == informTime.length == n
Topics

Iterative DFS with Arrival Times

A subordinate receives the news after its manager’s arrival time plus the manager’s informTime. Track those arrival times and return their maximum.

javascript
function numOfMinutes(n, headID, manager, informTime) {
  const children = Array.from({ length: n }, () => []);
  for (let i = 0; i < n; i++) if (manager[i] !== -1) children[manager[i]].push(i);
  const stack = [[headID, 0]];
  let total = 0;
  while (stack.length) {
    const [id, time] = stack.pop();
    total = Math.max(total, time);
    for (const child of children[id]) stack.push([child, time + informTime[id]]);
  }
  return total;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript