![]() |
VOOZH | about |
Given an undirected tree of N vertices and N-1 edges. But now a friend has added an extra edge to the tree. You have to find an edge that your friend could have added. If there are multiple such possible edges then Print any.
Examples:
Input: N = 3, edges:[[1 2], [1 3], [2 3]]
Output: [2 3]
Explanation: We can remove any one of the three edges to get a valid tree.Input: N=5 edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1, 4]
Explanation: If we remove the edge [1, 5], the tree structure will be lost, and we will have two disconnected components (subtrees). Any edge apart from [1, 5] can be removed to get a valid tree.
Approach: To solve the problem follow the below idea:
The approach used in this code is Union-Find, also known as Disjoint Set Union (DSU). We will store the root parent of a node as well as the size of the subtree in one array parent[].
- If parent[i] is positive, then it means that parent[i] is the parent of node i
- If parent[i] is negative, then it means that the current node is the root parent of its set and the size of the set is the absolute value of parent[i].
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach:
2 3
Time complexity: O(E * ????(N)), where N is the number of nodes, E is the number of edges in the graph and ????(N) is the Inverse Ackermann Function which grows very slowly.
Auxiliary Space: O(N), where N is the number of nodes in the graph.