[LeetCode] Time Needed to Inform All Employees

1376. Time Needed to Inform All Employees

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.

Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.

The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.

The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).

Return the number of minutes needed to inform all the employees about the urgent news.

  • dynamic programming solution
  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
int dp[100000];
int dfs(int id, vector<int>& manager, vector<int>& informTime) {
if(dp[id] != -1) return dp[id];
return dp[id] = dfs(manager[id], manager, informTime) + informTime[manager[id]];
}
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
if(n == 1) return 0;
memset(dp, -1, sizeof(dp));
dp[headID] = 0;
int res = 0;
for(int i = 0; i < n; i++) {
res = max(res, dfs(i,manager,informTime));
}
return res;
}
};
  • topology sort + bfs solution
  • Time : O(n) (all nodes are connected witch is 2n, so it calls n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
if(n == 1) return 0;
unordered_map<int, vector<int>> subordinates;
for(int i = 0; i < n; i++) {
if(i == headID) continue;
subordinates[manager[i]].push_back(i);
}

queue<pair<int, int>> q;
q.push({headID,0});
int res = 0;
while(!q.empty()) {
auto [id, time] = q.front(); q.pop();
res = max(time, res);
for(auto subordinate : subordinates[id]) {
q.push({subordinate, time + informTime[id]});
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/13/PS/LeetCode/time-needed-to-inform-all-employees/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.