Phone tree broadcast
HardOnline Assessment
Work out how long a phone tree takes to spread news, for every office as the starting point.
A company has n offices, numbered 0 to n - 1, connected by n - 1 phone lines so that every office can reach every other through exactly one chain of lines (a tree). The lines are given by parents: office i + 1 has a line to office parents[i], where parents[i] <= i.
When news starts at an office, that office learns it at minute 0. An office that learns the news at minute T then phones its neighbours that have not yet heard it (every neighbour except the one that phoned it). It can make one call per minute: its first call goes out at minute T + 1, the next at T + 2, and so on, in whatever order it likes. A call is answered instantly, so the neighbour learns the news at the minute of the call, and then starts phoning its own other neighbours the same way. Each office chooses its call order to finish as early as possible.
Input: n, the number of offices, and parents, as described above.
Output: a list of n integers: element r is the minute at which the last office learns the news when the news starts at office r. A single office gives [0]; with no offices, return [].
Simulating every starting office separately will be too slow for large trees.
Example 1
- Input:
- [5,[0,1,2,3]]
- Output:
- [4,3,3,3,4]
- Explanation
- The offices form a line 0-1-2-3-4. Starting at office 1, it phones office 2 first (minute 1): offices 3 and 4 then hear at minutes 2 and 3. Office 0 is phoned at minute 2. Everyone knows by minute 3. If office 1 phoned office 0 first, the far end would only be reached at minute 4. The ends need 4 minutes and the three inner offices 3 minutes: [4, 3, 3, 3, 4].
Example 2
- Input:
- [6,[0,0,0,1,1]]
- Output:
- [3,3,4,4,4,4]
- Explanation
- Office 0 has branches 1, 2, 3, and office 1 has the extra branches 4 and 5. Starting at office 0, it phones office 1 first (office 1 needs 2 more minutes for 4 and 5, so minute 3), then 2 and 3 at minutes 2 and 3: done at minute 3. Starting at the leaf 2, it phones office 0 at minute 1, and office 0 then needs 3 more minutes for the rest (1 at minute 1 plus its 2, then 3), so everyone knows by minute 4: [3, 3, 4, 4, 4, 4].
Example 3
- Input:
- [7,[0,0,1,1,2,2]]
- Output:
- [4,4,4,5,5,5,5]
- Explanation
- A balanced tree of seven offices. Starting at the top office everyone knows by minute 4 (it phones one child at minute 1 and the other at minute 2, and each child needs 2 more minutes). Starting at a leaf takes 5 minutes: the leaf phones its parent (minute 1), who must reach the sibling leaf and the whole other half of the tree, which takes 4 more minutes: [4, 4, 4, 5, 5, 5, 5].
Constraints
0 <= n <= 3,500parents.length == max(0, n - 1), and0 <= parents[i] <= ifor everyi