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 Trees0123Tree 101Tree 2Connect with bridge edgeGoal: Find the connection that minimizes the diameterDiameter = longest path between any two nodesMust try different connection points to find minimumOutput: Minimum possible diameter = 3
Understanding the Visualization
1
Input
Two separate trees with their edge lists
2
Process
Connect one node from each tree with a bridge edge
3
Output
Minimum possible diameter of the merged tree
Key Takeaway
🎯 Key Insight: Connect the centers of both trees to minimize the maximum distance between any two nodes
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