Problem

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 kNote 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 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.

Example 1:

graph LR

    subgraph Tree1["Tree 1"]
		A(0) --- B(1)
		A(0) --- C(2)
		C(2) --- D(3)
		C(2) --- E(4)
    end
    
    subgraph Tree2["Tree 2"]
		A2(0) --- B2(1)
		A2(0) --- C2(2)
		A2(0) --- D2(3)
		C2(2) --- G2(7)
		B2(1) --- E2(4)
		E2(4) --- F2(5)
		E2(4) --- H2(6)
    end
    
    
	Tree1 ~~~ Tree2
  
1
2
3
4
5
6
7
8
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 = 2
Output: [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.

Example 2:

 graph LR
 
     subgraph Tree1["Tree 1"]
 		A(0) --- B(1)
 		A(0) --- C(2)
 		A(0) --- D(3)
 		A(0) --- E(4)
     end
     
     subgraph Tree2["Tree 2"]
 		A2(0) --- B2(1)
 		B2(1) --- C2(2)
 		C2(2) --- D2(3)
     end
     
     
 	Tree1 ~~~ Tree2
  
1
2
3
4
Input: edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1
Output: [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.
  • 0 <= k <= 1000

Examples

Solution

Method 1 - Using DFS

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:

  1. count1[i]: The number of nodes in the first tree within a distance ≤ k from node i.
  2. 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).

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {

    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {
        int n = edges1.length + 1, m = edges2.length + 1;

        // Precompute reachable counts
        int[] count1 = precomputeDFS(edges1, k);
        int[] count2 = precomputeDFS(edges2, k - 1);

        // Find the maximum count from the second tree
        int maxCount2 = 0;
        for (int c : count2) {
            maxCount2 = Math.max(maxCount2, c);
        }

        // Compute the results using count1 and maxCount2
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = count1[i] + maxCount2;
        }
        return res;
    }

    // Build adjacency list and compute reachable counts using DFS
    private int[] 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 = new int[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`
    private int dfs(List<List<Integer>> tree, int node, int parent, int k) {
        if (k < 0) {
            return 0;
        }
        int count = 1; // Current node counts as reachable
        for (int neighbour : tree.get(node)) {
            if (neighbour != parent) {
                count += dfs(tree, neighbour, node, k - 1);
            }
        }
        return count;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
    def maxTargetNodes(self, edges1: List[List[int]], edges2: List[List[int]], k: int) -> List[int]:
        def precompute_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
        
        def dfs(tree: defaultdict, node: int, parent: int, k: int) -> int:
            if k < 0:
                return 0
            count = 1  # Include the current node
            for 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 results
        return [count1[i] + max_count2 for i in range(n)]

Complexity

  • ⏰ 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.