1651. Nodes on a Longest Road
A kingdom has n towns numbered 0 to n-1 joined by n-1 two-way roads so that every town can reach every other by exactly one route; the roads are listed in edges as pairs [u, v]. The length of a route is its number of roads.
A route is a longest road if no route anywhere in the kingdom is longer. Several different longest roads may exist, sharing towns or not. Return how many towns lie on at least one longest road (a lone town counts when n = 1, since the route of length 0 is the longest).
Trees can be paths 10^5 towns long, so use an iterative traversal. Aim for O(n) time and O(n) space.
Example 1
- Input:
- n = 6, edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
- Output:
- 5
- Explanation:
The longest road is 3-2-1-4-5 with 4 edges, so those five nodes qualify while node 0 does not.
Example 2
- Input:
- n = 4, edges = [[0,1],[0,2],[0,3]]
- Output:
- 4
- Explanation:
Every pair of leaves is joined by a road of 2 edges through node 0, so all four nodes lie on a longest road.
Constraints
1 ≤ n ≤ 105
edges has n - 1 pairs [u, v] with 0 ≤ u, v < n and forms a tree
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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)