1648. Bridge Two Kingdoms
Two separate kingdoms each have their towns joined by two-way roads so that, inside a kingdom, any two towns are connected by exactly one route. The first kingdom has edgesA.length + 1 towns numbered from 0 and the second has edgesB.length + 1 towns, also numbered from 0; the roads are given as pairs [u, v]. A kingdom may be a single town with no roads.
The rulers will build exactly one new road between one town of the first kingdom and one town of the second, choosing both ends freely. The length of a route is its number of roads, and the span of the merged kingdom is the length of its longest route. Return the smallest span that can be achieved.
Aim for O(n) time and O(n) space, where n is the total number of towns; use an iterative traversal.
Example 1
- Input:
- edgesA = [[0,1],[1,2],[2,3]], edgesB = [[0,1],[0,2]]
- Output:
- 4
- Explanation:
The first kingdom is a chain of 4 towns (diameter 3) and the second a path of 3 towns (diameter 2); linking the middle of each gives a longest road of 4.
Example 2
- Input:
- edgesA = [], edgesB = []
- Output:
- 1
- Explanation:
Two single towns joined by the new road form a pair of towns, so the longest road has length 1.
Constraints
0 ≤ edgesA.length, edgesB.length < 50000
Each list holds pairs [u, v] with 0 ≤ u, v ≤ its own length and forms a tree on towns 0..length
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)