Find Minimum Diameter After Merging Two Trees - Problem

There exist two undirected trees with n and m nodes, numbered from 0 to n - 1 and from 0 to m - 1, respectively.

You are given two 2D integer arrays edges1 and edges2 of lengths n - 1 and m - 1, respectively, where edges1[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the first tree and edges2[i] = [ui, vi] indicates that there is an edge between nodes ui and vi in the second tree.

You must connect one node from the first tree with another node from the second tree with an edge.

Return the minimum possible diameter of the resulting tree. The diameter of a tree is the length of the longest path between any two nodes in the tree.

Input & Output

Example 1 — Basic Case
$ Input: edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]
Output: 3
💡 Note: Tree1 has diameter 2 (from node 1 to 3 via 0). Tree2 has diameter 1. Connecting centers gives diameter 3.
Example 2 — Linear Trees
$ Input: edges1 = [[0,1],[1,2],[1,3]], edges2 = [[0,1],[1,2]]
Output: 4
💡 Note: Both trees are somewhat linear. The optimal connection results in diameter 4.
Example 3 — Single Nodes
$ Input: edges1 = [], edges2 = []
Output: 1
💡 Note: Two single nodes connected by one edge results in diameter 1.

Constraints

  • 1 ≤ n, m ≤ 105
  • edges1.length == n - 1
  • edges2.length == m - 1
  • 0 ≤ ai, bi < n
  • 0 ≤ ui, vi < m
  • The input is guaranteed to be two trees

Visualization

Tap to expand
Find Minimum Diameter After Merging Two Trees INPUT Tree 1 (4 nodes) 0 1 2 3 Diameter = 2 Tree 2 (2 nodes) 0 1 Diameter = 1 edges1 = [[0,1],[0,2],[0,3]] edges2 = [[0,1]] n=4 nodes, m=2 nodes ALGORITHM STEPS 1 Find Diameters d1=2 (Tree1), d2=1 (Tree2) 2 Find Centers Node 0 (Tree1), Node 0/1 (Tree2) 3 Calculate Radii r1=ceil(2/2)=1, r2=ceil(1/2)=1 4 Compute Result max(d1, d2, r1+r2+1) Formula: max(d1, d2, r1 + r2 + 1) = max(2, 1, 1 + 1 + 1) = 3 Connect Centers: 0 0 new edge T1 T2 FINAL RESULT Merged Tree 0 1 2 3 0 1 Longest Path (diameter=3): 1 0 0 1 3 edges Output: 3 OK - Minimum diameter achieved! Key Insight: To minimize the diameter after merging, connect the CENTER nodes of both trees. The center minimizes the maximum distance to all other nodes (radius = ceil(diameter/2)). Result = max(d1, d2, ceil(d1/2) + ceil(d2/2) + 1) where the +1 is the connecting edge. TutorialsPoint - Find Minimum Diameter After Merging Two Trees | Optimal - Connect Tree Centers
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
8.8K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen