Payments app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1376tree-recursion · dfs
A payments app has an on-call tree. When an incident is declared, the head of operations is told first. Every person who has heard then phones their direct reports, and those reports pass the news on in the same way.
A person needs a fixed number of minutes to reach all of their direct reports, and all of them hear at the same moment. Your team lead asks: how many minutes pass until the last person has heard?
Write minutes_to_inform_all(managers, times).
0 to n - 1. managers[i] is the direct manager of person i. The one person with -1 is the head, who hears at minute 0.times[i] is the number of minutes person i needs to inform all of their direct reports, once person i has heard. A person with no reports never uses it.Input: managers = [4, 5, -1, 5, 6, 2, 7, 2], times = [0, 0, 5, 0, 1, 4, 3, 2]
Output: 11Person 2 is the head, with 5 minutes for the reports 5 and 7. Person 5 has 4 minutes for 1 and 3.
Person 7 has 2 minutes for 6. Person 6 has 3 minutes for 4, and person 4 has 1 minute for 0.
A person hears when their manager has heard, plus the manager's time. Work through the people in order, and climb the chain of managers only until someone whose minute is known.
| Person | Chain climbed | Minute heard | Latest so far |
|---|---|---|---|
0 |
0, 4, 6, 7 |
11 | 11 |
1 |
1, 5 |
9 | 11 |
2 |
none, the head | 0 | 11 |
3 |
3 |
9 | 11 |
4 to 7 |
none, already known | 10, 5, 7, 5 | 11 |
Person 0 hears last, at minute 11: 5 from the head, then 2, then 3, then 1.
Input: managers = [-1, 0], times = [3, 9]
Output: 3The head needs 3 minutes. The other person has 9 minutes, but nobody to inform, so it is never used.
Input: managers = [-1], times = [7]
Output: 0The head is alone, and hears at minute 0.
1 ≤ length of managers = length of times ≤ 10^50 ≤ times[i] ≤ 1000managers[i] is -1, and every other entry is a person number from 0 to n - 1Adding up the managers above each person is fast when the tree is shallow. On a chain of 100,000 people, a person at the bottom has 100,000 managers above, and doing that for every person costs about 5 x 10^9 steps.
A chain also makes nested calls 100,000 deep, more than Python allows by default. Use a loop. The answer is at most 10^8, so a 32-bit integer holds it.