Skip to main content

Maximize the Number of Target Nodes After Connecting Trees I - Solution & Explanation

MediumTreeDepth-First SearchBreadth-First Search22 min readAsked at: Jio, Google
Practice this problem

Problem Statement

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 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:

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:

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

Approach Overview

Problem Overview: You are given two separate trees. You may connect exactly one node from the first tree to one node from the second tree with a new edge. For every node in the first tree, compute the maximum number of target nodes reachable within distance k after the connection is made. The goal is to choose the best node in the second tree so the reachable node count is maximized.

Approach 1: Breadth-First Search (BFS) Traversal (O(n^2 + m^2) time, O(n + m) space)

Treat both trees independently first. For each node in tree1, run a BFS to count how many nodes are within distance k. This produces an array where count1[i] represents reachable nodes if traversal stays inside tree1. Next, evaluate tree2 separately. Because one connecting edge consumes one step, nodes in tree2 must be within distance k-1 from the chosen connection node. Run BFS from every node in tree2 and compute how many nodes fall within distance k-1, then keep the maximum value. That maximum can be paired with any node in tree1 because you can always connect to the best node in tree2. The final answer for each node i becomes count1[i] + bestTree2. This approach works well because BFS naturally explores nodes level by level and stops once distance exceeds k. Tree traversal details rely on standard Breadth-First Search techniques.

Approach 2: Depth-First Search (DFS) with Memoization (O(n^2 + m^2) time, O(n + m) space)

The same distance counting can be implemented using recursive DFS. From each starting node, perform a depth-limited DFS that stops once the remaining distance becomes negative. Memoization can cache partial results for (node, remainingDistance) to avoid recomputing overlapping subtrees. This is useful when multiple DFS traversals revisit the same subtree with the same remaining distance. The logic mirrors the BFS approach: compute reachable counts within distance k for nodes in tree1 and within k-1 for nodes in tree2, then combine them using the maximum value from tree2. DFS implementations rely on adjacency lists and recursive traversal patterns from Depth-First Search on a tree.

Recommended for interviews: The BFS approach is usually expected. It is straightforward, avoids recursion depth issues, and clearly models the distance constraint. Showing the brute-force BFS from every node demonstrates understanding of tree traversal, while recognizing that the second tree only needs the global maximum shows the optimization insight interviewers look for.

Approach 1: Breadth-First Search (BFS) Based Approach

The idea is to calculate the number of target nodes for each node in both trees initially using a BFS traversal, given the constraint 'k'. After obtaining these counts, for each node in the first tree, try connecting it with every node in the second tree and compute the maximum target nodes considering the nodes in the second tree.

This approach leverages BFS to efficiently compute reachability within 'k' edges by using level-order traversal.

This solution involves breaking down the existing trees into adjacency lists and calculating the reachable node counts within 'k' distance using BFS. Subsequently, it integrates both trees by evaluating each node's reachability from the first to the second tree, providing a combined reachability value for node targets.

Code

Python

C

Java

Complexity

Time Complexity: O(N * M * K), where N is the number of nodes in the first tree, M is the number of nodes in the second tree, and K is the target distance threshold.

Space Complexity: O(N + M), considering the space for adjacency lists and auxiliary structures used during traversal.

Try this approach in the editor →

Approach 2: Depth-First Search (DFS) Based Approach with Memoization

This approach leverages DFS to find the number of target nodes reachable within 'k' from each node, utilizing memoization to store already computed results. By efficiently storing the DFS traversal results, we reduce redundant calculations, improving performance for larger graphs.

The integration of memoization with depth-first traversal provides an efficient matrix to determine targets when interlinking trees.

This solution builds trees using undirected edges and applies DFS with memoization to calculate reachable nodes efficiently within 'k'. The results are aggregated by finding the potential target nodes the first tree could exploit from the second tree.

Code

C++

JavaScript

Complexity

Time Complexity: O(N * M), where N and M represent the number of nodes in the respective trees.
Space Complexity: O(N * K) due to memoization array usage.

Try this approach in the editor →

Approach 3: Enumeration + DFS

According to the problem description, to maximize the number of target nodes for node i, we must connect node i to one of the nodes j in the second tree. Therefore, the number of target nodes for node i can be divided into two parts:

  • In the first tree, the number of nodes reachable from node i within a depth of k.
  • In the second tree, the maximum number of nodes reachable from any node j within a depth of k - 1.

Thus, we can first calculate the number of nodes reachable within a depth of k - 1 for each node in the second tree. Then, we enumerate each node i in the first tree, calculate the sum of the two parts mentioned above, and take the maximum value.

The time complexity is O(n^2 + m^2), and the space complexity is O(n + m). Here, n and m are the number of nodes in the two trees, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Breadth-First Search (BFS) Based Approach

Time Complexity: O(N * M * K), where N is the number of nodes in the first tree, M is the number of nodes in the second tree, and K is the target distance threshold.

Space Complexity: O(N + M), considering the space for adjacency lists and auxiliary structures used during traversal.

Depth-First Search (DFS) Based Approach with Memoization

Time Complexity: O(N * M), where N and M represent the number of nodes in the respective trees.
Space Complexity: O(N * K) due to memoization array usage.

Enumeration + DFS—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
BFS Traversal from Every NodeO(n^2 + m^2)O(n + m)Best general approach for medium constraints and easiest to implement
DFS with MemoizationO(n^2 + m^2)O(n + m)Useful when recursion with distance pruning is preferred or when caching subtree results

Video Solution

Maximize the Number of Target Nodes After Connecting Trees I | BFS | DFS | Leetcode 3372 | MIK • codestorywithMIK • 10,294 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Maximize the Number of Target Nodes After Connecting Trees I easy or hard?
The problem is rated Medium. The main challenge is recognizing that the optimal node from the second tree can be computed independently and reused for every node in the first tree, which simplifies the overall logic.
Maximize the Number of Target Nodes After Connecting Trees I Python/Java solution
Implementations typically build adjacency lists for both trees and run BFS from each node to count reachable nodes within the allowed distance. The same logic works in Python, Java, C, or C++ because the algorithm relies only on graph traversal and queue operations.
How to solve Maximize the Number of Target Nodes After Connecting Trees I in O(n)?
A strict O(n) solution is difficult because the problem requires distance-based counts from multiple nodes. Most accepted implementations run BFS or DFS from each node to count nodes within distance k. Optimizations mainly focus on reusing the maximum value from tree2 rather than recomputing combinations for every node.
What is the best approach for Maximize the Number of Target Nodes After Connecting Trees I?
The most practical approach is running Breadth-First Search (BFS) from each node in both trees. Compute how many nodes in tree1 are within distance k and find the maximum number of nodes reachable within distance k-1 from any node in tree2. Combining these values gives the optimal result for every node in tree1.
Is Maximize the Number of Target Nodes After Connecting Trees I asked at Google/Amazon/Meta?
Tree traversal and distance-counting problems similar to this appear frequently in interviews at companies like Amazon, Google, and Meta. The exact problem may not appear verbatim, but BFS or DFS on trees with distance constraints is a common interview pattern.
What data structure is used in Maximize the Number of Target Nodes After Connecting Trees I?
The solution primarily uses adjacency lists to represent both trees, along with a queue for BFS or recursion stack for DFS. These structures allow efficient traversal and distance tracking while exploring neighbors in the tree.
What is the time complexity of Maximize the Number of Target Nodes After Connecting Trees I?
The typical solution runs BFS or DFS from every node in each tree. For trees with n and m nodes, this results in O(n^2 + m^2) time in the worst case, with O(n + m) auxiliary space for adjacency lists and traversal queues.

Ready to solve this problem?

Practice Maximize the Number of Target Nodes After Connecting Trees I with our built-in code editor and test cases.

Practice on FleetCode