Ctrl K

Joining Two Trees

Hard
You get two undirected trees. The first has n nodes numbered 0 to n − 1, and its edges are in first_edges, where [a, b] is an edge between nodes a and b. The second has m nodes numbered 0 to m − 1 and edges second_edges. Add one new edge between some node of the first tree and some node of the second, which makes one big tree. Pick the endpoints so that the **diameter** of the result (the number of edges on the longest path between two nodes) is as small as possible, and return that diameter.
Example 1
first_edges=[[0, 1], [1, 2]], second_edges=[[0, 1], [0, 2], [0, 3]] → 3

Join the middle of the first chain (node 1) to the center of the second tree (node 0). The longest path, for instance from node 0 of the first tree to a leaf of the second, has length 3.

Example 2
first_edges=[], second_edges=[[0, 1]] → 2

The first tree is a single node. Whichever end of the second tree it is attached to, the result is a three-node chain of length 2.

Example 3
first_edges=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]], second_edges=[] → 5

The first tree already has diameter 5, and no new edge can shrink it. Hanging the single node off node 2 or 3 keeps every path at most 5 long.

Constraints
  • 1 ≤ n, m ≤ 10⁵
  • len(first_edges) == n − 1, len(second_edges) == m − 1
  • Node numbers are below n in the first tree and below m in the second
  • Each edge list forms a tree
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsA Beetle Wandering a Tree HardLongest Hike Through the Woods MediumLinks That Form a Single Tree MediumRooms Open from the Hall MediumTreasure Gates Race Medium
loading Python…
Input
first_edges=[[0, 1], [1, 2]], second_edges=[[0, 1], [0, 2], [0, 3]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 61 tests on the server, hidden ones included.