2024-12-24 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp
.
December LeetCoding Challenge 24
Description
Find Minimum Diameter After Merging Two Trees
There exist two undirected trees with n
and m
nodes, numbered from 0
to n - 1
and from 0
to 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 must connect one node from the first tree with another node from the second tree with an edge.
Return the minimum possible diameter of the resulting tree.
The diameter of a tree is the length of the longest path between any two nodes in the tree.
Example 1:
Input: edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]
Output: 3
Explanation:
We can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.
Example 2:
Input: edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]
Output: 5
Explanation:
We can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.
Constraints:
1 <= 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
andedges2
represent valid trees.
Solution
class Solution {
void dfs(
int current,
int parent,
int &furthest,
vector<int> &distance,
const vector<vector<int>> &neighbors
) {
for(auto next : neighbors[current]) {
if(next == parent) continue;
distance[next] = distance[current] + 1;
if(distance[next] > distance[furthest]) furthest = next;
dfs(next, current, furthest, distance, neighbors);
}
}
int diameter(vector<vector<int>> & edges) {
int n = edges.size() + 1;
vector<vector<int>> neighbors(n);
for(auto &e : edges) {
neighbors[e[0]].push_back(e[1]);
neighbors[e[1]].push_back(e[0]);
}
vector<int> distance(n, 0);
int start = 0;
dfs(0, -1, start, distance, neighbors);
int end = start;
distance[start] = 0;
dfs(start, -1, end, distance, neighbors);
return distance[end];
}
public:
int minimumDiameterAfterMerge(vector<vector<int>>& edges1, vector<vector<int>>& edges2) {
int d1 = diameter(edges1);
int d2 = diameter(edges2);
return max({d1, d2, (d1 + 1) / 2 + (d2 + 1) / 2 + 1});
}
};
// Accepted
// 723/723 cases passed (303 ms)
// Your runtime beats 55.76 % of cpp submissions
// Your memory usage beats 53.58 % of cpp submissions (305.5 MB)