Talentd
FleetCode
Make and follow sheets.Sign in

Maximize the Number of Target Nodes After Connecting Trees II solution and explanation

HardBreadth-First SearchDepth-First SearchTree7 min read72.5% acceptanceUpdated 9 Apr 2026
Maximize the Number of Target Nodes After Connecting Trees II | Full Dry Run | Leetcode 3373 | MIKcodestorywithMIK · 48:20 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Maximize the Number of Target Nodes After Connecting Trees II | Full Dry Run | Leetcode 3373 | MIKcodestorywithMIK · 48:20 · 6K views
  2. Maximize the Number of Target Nodes After Connecting Trees II | Leetcode 3373Techdose · 27:33 · 3K views
  3. 3373. Maximize the Number of Target Nodes After Connecting Trees II | Graph | DP on Trees | GreedyAryan Mittal · 27:32 · 2K views
  4. 3373. Maximize the Number of Target Nodes After Connecting Trees II - Day 29/31 Leetcode May ChallenProgramming Live with Larry · 27:06 · 459 views
  5. 3373. Maximize the Number of Target Nodes After Connecting Trees II (Leetcode Hard)Programming Live with Larry · 12:08 · 276 views
  6. Maximize the Number of Target Nodes After Connecting Trees II | LeetCode 3373 - Pythonimpoldev · 13:11 · 271 views
  7. LeetCode 3373 - Maximize the Number of Target Nodes After Connecting Trees II - JavaAlpha-Code · 9:53 · 177 views
  8. Leetcode 3373. Maximize the Number of Target Nodes After Connecting Trees II | Parity Trick + DFSStatLearn Tech · 19:45 · 131 views
  9. 3373. Maximize the Number of Target Nodes After Connecting Trees II | Weekly Contest 426 | LeetcodeAmit Choraria · 17:05 · 103 views
  10. 3373. Maximize the Number of Target Nodes After Connecting Trees II | Leetcode Daily - PythonLeetcode Daily · 6:25 · 91 views

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

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

Output: [8,7,7,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 4 from the second tree.
  • For i = 2, connect node 2 from the first tree to node 7 from the second tree.
  • For i = 3, connect node 3 from the first tree to node 0 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]]

Output: [3,6,6,6,6]

Explanation:

For every i, connect node i of the first tree with any node of the second tree.

Constraints:

  • 2 <= n, m <= 105
  • 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.

Approach overview

Problem Overview: You are given two trees. You may connect one node from the first tree to any node in the second tree. After adding this edge, determine for every node in the first tree the maximum number of target nodes reachable at even distance. The challenge is choosing the best connection point in the second tree while efficiently computing parity distances.

Approach 1: DFS with Pre-computed Parities (O(n + m) time, O(n + m) space)

Trees are bipartite by nature. If you run a depth-first search on each tree, you can assign every node a parity (0 for even depth, 1 for odd depth). Count how many nodes belong to each parity group. For the first tree, each node already knows how many nodes are at even distance within its own tree based on its parity group. For the second tree, you only need the larger of the two parity groups because you can connect the trees in a way that flips parity if beneficial. Iterate through nodes in tree1 and combine its reachable even-parity count with the best possible count from tree2. This avoids recomputing distances for every possible connection.

The key insight: adding a single edge toggles parity depending on which nodes you connect. Because parity is all that matters for even-distance checks, precomputing counts for both parity sets gives the optimal answer immediately.

Approach 2: Dynamic Programming with Path Parity Tracking (O(n + m) time, O(n + m) space)

Another approach tracks parity contributions using reroot-style tree dynamic programming. Run a traversal on each tree and compute how many nodes are reachable with even and odd parity from every node. While traversing, propagate counts to children while flipping parity as edges are crossed. This technique resembles rerooting DP frequently used in tree problems. After computing parity distributions, evaluate the best connection between the two trees by combining compatible parity groups. Although the complexity matches the DFS approach, the implementation is more involved because state transitions must correctly adjust parity counts.

Traversal can be implemented with either DFS or BFS. Both produce the same parity labeling since the graph is a tree.

Recommended for interviews: The DFS parity counting approach. It demonstrates recognition of the bipartite property of trees and reduces the problem to simple counting instead of repeated path calculations. Mentioning the brute-force idea (checking every connection with repeated traversals) shows understanding, but the parity observation is the optimization interviewers expect.

Approach 1: DFS with Pre-computed Parities

To determine the maximum number of nodes in the second tree that are 'target' to a specific node in the first tree, explore the parity of paths in each tree independently using Depth First Search (DFS). For each source node in the first tree, connect it with each node in the second tree to compute the union of target nodes. This requires understanding how the parity of the path from the source node to another node affects its 'target' status.

/* Python code for DFS solution */
/* Java code for DFS solution */
/* C++ code for DFS solution */
/* JavaScript code for DFS solution */
/* C code for DFS solution */
/* C# code for DFS solution */

Here, a Python solution uses recursive DFS traversals to assess which connections maximize target nodes for each query node. BFS might assist in initial level calculations; however, DFS filters valid nodes subsequently.

Complexity

Time Complexity: O(n * m)
Space Complexity: O(n + m)

Try this approach in the editor

Approach 2: Dynamic Programming with Path Parity Tracking

Alternatively, use dynamic programming to track path parities across disjoint subproblems. Here, linked lists or adjacency tables establish node connections. By leveraging dynamic techniques, each node's potential 'target' connections are recursively built and stored, facilitating rapid evaluations.

/* Python code for DP solution */
/* Java code for DP solution */
/* C++ code for DP solution */
/* JavaScript code for DP solution */
/* C code for DP solution */
/* C# code for DP solution */

The DP approach in Python simplifies complex state tracking using dictionaries and lists. Intermediate values are recorded to manage the cost of expanded tree connections.

Complexity

Time Complexity: O(n * m)
Space Complexity: O(n + m)

Try this approach in the editor

Approach 3: DFS

The number of target nodes for node i can be divided into two parts:

  • The number of nodes in the first tree with the same depth parity as node i.
  • The maximum number of nodes in the second tree with the same depth parity.

First, we use Depth-First Search (DFS) to calculate the number of nodes in the second tree with the same depth parity, denoted as cnt2. Then, we calculate the number of nodes in the first tree with the same depth parity as node i, denoted as cnt1. Therefore, the number of target nodes for node i is max(cnt2) + cnt1.

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

function maxTargetNodes(edges1: number[][], edges2: number[][]): number[] {
    const g1 = build(edges1);
    const g2 = build(edges2);
    const [n, m] = [g1.length, g2.length];
    const c1 = Array(n).fill(0);
    const c2 = Array(m).fill(0);
    const cnt1 = [0, 0];
    const cnt2 = [0, 0];

    dfs(g2, 0, -1, c2, 0, cnt2);
    dfs(g1, 0, -1, c1, 0, cnt1);

    const t = Math.max(...cnt2);
    const ans = Array(n);
    for (let i = 0; i < n; i++) {
        ans[i] = t + cnt1[c1[i]];
    }
    return ans;
}

function build(edges: number[][]): number[][] {
    const n = edges.length + 1;
    const g: number[][] = Array.from({ length: n }, () => []);
    for (const [a, b] of edges) {
        g[a].push(b);
        g[b].push(a);
    }
    return g;
}

function dfs(g: number[][], a: number, fa: number, c: number[], d: number, cnt: number[]): void {
    c[a] = d;
    cnt[d]++;
    for (const b of g[a]) {
        if (b !== fa) {
            dfs(g, b, a, c, d ^ 1, cnt);
        }
    }
}
func maxTargetNodes(edges1 [][]int, edges2 [][]int) []int {
    g1 := build(edges1)
    g2 := build(edges2)
    n, m := len(g1), len(g2)
    c1 := make([]int, n)
    c2 := make([]int, m)
    cnt1 := make([]int, 2)
    cnt2 := make([]int, 2)

    dfs(g2, 0, -1, c2, 0, cnt2)
    dfs(g1, 0, -1, c1, 0, cnt1)

    t := max(cnt2[0], cnt2[1])
    ans := make([]int, n)
    for i := 0; i < n; i++ {
        ans[i] = t + cnt1[c1[i]]
    }
    return ans
}

func build(edges [][]int) [][]int {
    n := len(edges) + 1
    g := make([][]int, n)
    for _, e := range edges {
        a, b := e[0], e[1]
        g[a] = append(g[a], b)
        g[b] = append(g[b], a)
    }
    return g
}

func dfs(g [][]int, a, fa int, c []int, d int, cnt []int) {
    c[a] = d
    cnt[d]++
    for _, b := range g[a] {
        if b != fa {
            dfs(g, b, a, c, d^1, cnt)
        }
    }
}
impl Solution {
    pub fn max_target_nodes(edges1: Vec<Vec<i32>>, edges2: Vec<Vec<i32>>) -> Vec<i32> {
        fn build(edges: &Vec<Vec<i32>>) -> Vec<Vec<i32>> {
            let n = edges.len() + 1;
            let mut g = vec![vec![]; n];
            for e in edges {
                let a = e[0] as usize;
                let b = e[1] as usize;
                g[a].push(b as i32);
                g[b].push(a as i32);
            }
            g
        }

        fn dfs(g: &Vec<Vec<i32>>, a: usize, fa: i32, c: &mut Vec<i32>, d: i32, cnt: &mut Vec<i32>) {
            c[a] = d;
            cnt[d as usize] += 1;
            for &b in &g[a] {
                if b != fa {
                    dfs(g, b as usize, a as i32, c, d ^ 1, cnt);
                }
            }
        }

        let g1 = build(&edges1);
        let g2 = build(&edges2);
        let n = g1.len();
        let m = g2.len();

        let mut c1 = vec![0; n];
        let mut c2 = vec![0; m];
        let mut cnt1 = vec![0; 2];
        let mut cnt2 = vec![0; 2];

        dfs(&g2, 0, -1, &mut c2, 0, &mut cnt2);
        dfs(&g1, 0, -1, &mut c1, 0, &mut cnt1);

        let t = cnt2[0].max(cnt2[1]);
        let mut ans = vec![0; n];
        for i in 0..n {
            ans[i] = t + cnt1[c1[i] as usize];
        }

        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
DFS with Pre-computed Parities

Time Complexity: O(n * m)
Space Complexity: O(n + m)

Dynamic Programming with Path Parity Tracking

Time Complexity: O(n * m)
Space Complexity: O(n + m)

DFS–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Recompute DistancesO(n * (n + m))O(n + m)Conceptual baseline; try every possible connection and run BFS/DFS each time
DFS with Pre-computed ParitiesO(n + m)O(n + m)Best practical solution; uses bipartite parity property of trees
Dynamic Programming with Path Parity TrackingO(n + m)O(n + m)Useful when extending to rerooting or multi-query tree problems

Frequently asked questions

Is Maximize the Number of Target Nodes After Connecting Trees II easy or hard?

The problem is rated Hard because it requires recognizing the bipartite parity property of trees and reducing the problem to parity counting. Without that insight, a brute-force solution that recomputes distances for each connection becomes too slow.

Maximize the Number of Target Nodes After Connecting Trees II Python/Java solution

Most implementations build adjacency lists for both trees, run DFS to label node parity, and count how many nodes belong to each parity set. The final answer for each node in the first tree combines its local parity count with the best parity group from the second tree. This approach translates directly to Python, Java, C++, C#, and JavaScript.

How to solve Maximize the Number of Target Nodes After Connecting Trees II in O(n)?

Traverse each tree once using DFS or BFS to assign depth parity (0 or 1). Count how many nodes belong to each parity group. For every node in the first tree, its reachable even-distance nodes come from its own parity group plus the larger compatible parity group in the second tree after connecting the edge. This reduces the problem to simple arithmetic after preprocessing.

What is the best approach for Maximize the Number of Target Nodes After Connecting Trees II?

The most efficient approach uses DFS to assign parity (even or odd depth) to every node in both trees. Because trees are bipartite, nodes split into two parity groups. Counting nodes in each group allows you to instantly determine how many nodes are reachable at even distance after adding the connecting edge. This yields an O(n + m) time solution.

Is Maximize the Number of Target Nodes After Connecting Trees II asked at Google/Amazon/Meta?

Tree traversal and parity-based reasoning problems frequently appear in interviews at companies like Google, Amazon, and Meta. While this exact problem may not always appear verbatim, similar questions involving bipartite properties, DFS traversal, and rerooting techniques are common in senior-level interviews.

What data structure is used in Maximize the Number of Target Nodes After Connecting Trees II?

The core data structure is an adjacency list representing each tree. Traversal algorithms such as Depth-First Search (DFS) or Breadth-First Search (BFS) compute node depth parity and count group sizes. Arrays or vectors store parity assignments and counts.

What is the time complexity of Maximize the Number of Target Nodes After Connecting Trees II?

The optimal solution runs in O(n + m) time where n and m are the number of nodes in the two trees. A single DFS or BFS traversal labels node parity and counts group sizes. After preprocessing, each node's answer is computed in constant time.

Comments

Now write it yourselfClose this page and solve Maximize the Number of Target Nodes After Connecting Trees II in the editor, without looking.
Practise Maximize the Number of Target Nodes After Connecting Trees II