1661. Farthest Reach per Node

Medium3.5 points estimatedTreeGraphBreadth-First Search

A rural network of n villages, numbered 0 to n-1, is joined by n - 1 two-way roads given in edges so that every village can be reached from every other one by exactly one route. The reach of a village is the number of roads on the route to the village farthest away from it.

Return an array of length n where entry i is the reach of village i. A single village has reach 0. Running a search from every village is far too slow for large inputs; instead use the fact that the farthest village from any village is always one of the two ends of a longest route in the network. Aim for O(n) time and O(n) space.

Example 1

Input:
n = 5, edges = [[0,1],[1,2],[1,3],[3,4]]
Output:
[3,2,3,2,3]
Explanation:

The longest route is 0-1-3-4 with 3 roads; village 1 and village 3 are at most 2 away, while 0, 2 and 4 are 3 away from their farthest village.

Example 2

Input:
n = 1, edges = []
Output:
[0]
Explanation:

A lone village has no roads, so its reach is 0.

Constraints

1 ≤ n ≤ 5*104; edges.length == n - 1; the edges form a tree on villages 0..n-1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…