Maximize the Number of Target Nodes After Connecting Trees II - Problem

There exist two undirected trees with n and m nodes, labeled from [0, n - 1] and [0, 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.

Node u is target to node v if the number of edges on the path from u to v is even. Note that a node is always target to itself.

Return an array of n integers answer, where answer[i] is the maximum possible number of nodes that are target to node i of the first tree if you had to connect one node from the first tree to another node in the second tree.

Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.

Input & Output

Example 1 — Basic Two-Node Trees
$ Input: edges1 = [[0,1]], edges2 = [[0,1]]
Output: [3,3]
💡 Note: Each tree has 2 nodes. When we connect them optimally, each node can reach 3 target nodes total (including nodes at even distances through the bridge connection).
Example 2 — Single Node Trees
$ Input: edges1 = [], edges2 = []
Output: [2]
💡 Note: Each tree has only 1 node. When connected, node 0 from tree1 can reach itself (distance 0, even) and the single node from tree2 (distance 1+0=1, odd). Actually, distance 1 is odd, so only itself at distance 0. The bridge adds 1 more reachable target.
Example 3 — Larger Trees
$ Input: edges1 = [[0,1],[1,2]], edges2 = [[0,1],[1,2]]
Output: [4,4,4]
💡 Note: Linear trees with 3 nodes each. Optimal bridge connections allow each query node to reach maximum target nodes with even path lengths.

Constraints

  • 1 ≤ n, m ≤ 1000
  • edges1.length = n - 1
  • edges2.length = m - 1
  • 0 ≤ ai, bi < n
  • 0 ≤ ui, vi < m
  • The input ensures that edges1 and edges2 represent valid trees

Visualization

Tap to expand
Maximize Target Nodes After Connecting Two Trees01Tree 101Tree 2Bridge ConnectionQuery: From node 0 in Tree 1, how many target nodes?Target = reachable via even-length path (0, 2, 4, ... edges)Goal: Find optimal bridge to maximize targets
Understanding the Visualization
1
Input Trees
Two separate undirected trees with given edge connections
2
Add Bridge
Connect one node from each tree to form a single connected graph
3
Count Targets
For each query node, count nodes reachable via even-length paths
Key Takeaway
🎯 Key Insight: Trees are bipartite graphs - leverage this property to efficiently compute optimal bridge connections
Asked in
Google 12 Meta 8 Amazon 6
8.5K Views
Medium Frequency
~35 min Avg. Time
245 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