There exist two undirected trees with n and m nodes, with distinct labels in ranges [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. You are also given an integer k.
Node u is target to node v if the number of edges on the path from u to v is less than or equal to k. Note that a node is alwaystarget to itself.
Return an array of n integers answer, where answer[i] is the maximum possible number of nodes target to node i of the first tree if you have 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: edges1 =[[0,1],[0,2],[2,3],[2,4]], edges2 =[[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k =2Output: [9,7,9,8,8]Explanation:
* For `i = 0`, connect node 0 from the first tree to node 0 from the second tree.* For `i = 1`, connect node 1 from the first tree to node 0 from the second tree.* For `i = 2`, connect node 2 from the first tree to node 4 from the second tree.* For `i = 3`, connect node 3 from the first tree to node 4 from the second tree.* For `i = 4`, connect node 4 from the first tree to node 4 from the second tree.
Input: edges1 =[[0,1],[0,2],[0,3],[0,4]], edges2 =[[0,1],[1,2],[2,3]], k =1Output: [6,3,3,3,3]Explanation:
For every `i`, connect node `i` of the first tree with any node of the second tree.
Constraints:
2 <= n, m <= 1000
edges1.length == n - 1
edges2.length == m - 1
edges1[i].length == edges2[i].length == 2
edges1[i] = [ai, bi]
0 <= ai, bi < n
edges2[i] = [ui, vi]
0 <= ui, vi < m
The input is generated such that edges1 and edges2 represent valid trees.
When the i-th node from the first tree is connected to a node j from the second tree, the distances from node i to nodes in the second tree reduce, making more nodes targetable.
To solve this, we need to calculate:
count1[i]: The number of nodes in the first tree within a distance ≤ k from node i.
count2[j]: The number of nodes in the second tree within a distance ≤ k-1 from node j. Since count2[j] is independent of the queries, we can precompute it for all j using Depth-First Search (DFS).
To determine the result for the i-th query, we compute count1[i] + maxCount2, where maxCount2 is the maximum value of count2[j] (computed across all nodes j in the second tree).
classSolution {
publicint[]maxTargetNodes(int[][] edges1, int[][] edges2, int k) {
int n = edges1.length+ 1, m = edges2.length+ 1;
// Precompute reachable countsint[] count1 = precomputeDFS(edges1, k);
int[] count2 = precomputeDFS(edges2, k - 1);
// Find the maximum count from the second treeint maxCount2 = 0;
for (int c : count2) {
maxCount2 = Math.max(maxCount2, c);
}
// Compute the results using count1 and maxCount2int[] res =newint[n];
for (int i = 0; i < n; i++) {
res[i]= count1[i]+ maxCount2;
}
return res;
}
// Build adjacency list and compute reachable counts using DFSprivateint[]precomputeDFS(int[][] edges, int k) {
int n = edges.length+ 1;
List<List<Integer>> tree =new ArrayList<>();
for (int i = 0; i < n; i++) {
tree.add(new ArrayList<>());
}
for (int[] edge : edges) {
tree.get(edge[0]).add(edge[1]);
tree.get(edge[1]).add(edge[0]);
}
int[] reachable =newint[n];
for (int i = 0; i < n; i++) {
reachable[i]= dfs(tree, i, -1, k);
}
return reachable;
}
// DFS to count reachable nodes within a distance of `k`privateintdfs(List<List<Integer>> tree, int node, int parent, int k) {
if (k < 0) {
return 0;
}
int count = 1; // Current node counts as reachablefor (int neighbour : tree.get(node)) {
if (neighbour != parent) {
count += dfs(tree, neighbour, node, k - 1);
}
}
return count;
}
}
classSolution:
defmaxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:
defprecompute_dfs(edges: List[List[int]], k: int) -> List[int]:
n = len(edges) +1 tree = defaultdict(list)
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
reachable = [0] * n
for i in range(n):
reachable[i] = dfs(tree, i, -1, k)
return reachable
defdfs(tree: defaultdict, node: int, parent: int, k: int) -> int:
if k <0:
return0 count =1# Include the current nodefor neighbour in tree[node]:
if neighbour != parent:
count += dfs(tree, neighbour, node, k -1)
return count
# Precompute reachable nodes for both trees n = len(edges1) +1 m = len(edges2) +1 count1 = precompute_dfs(edges1, k)
count2 = precompute_dfs(edges2, k -1)
# Find the maximum from the second tree max_count2 = max(count2)
# Combine the resultsreturn [count1[i] + max_count2 for i in range(n)]
⏰ Time complexity: O(n^2 + m^2) where n and m are the number of nodes in the first and second trees, respectively. 1. A DFS is performed starting from every node in each tree. Thus, the time complexity is O(n^2 + m^2).
🧺 Space complexity: O(n + m) for space required to store auxiliary arrays for both trees results.