![]() |
VOOZH | about |
Given a Directed rooted tree of N vertices and N-1 edges. But now your friend has added an extra edge in the tree. You have to find an edge that could have been added by your friend. If there are multiple such possible edge then Print any.
Examples:
Input: N=3 edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Explanation: the edge [2, 3] can be removed without disconnecting the graph.Input: N=5 edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]
Output: [4,1]
Explanation: the edge [4, 1] can be removed without disconnecting the graph. Removing this edge results in a connected graph structure: 1 -> 2, 2 -> 3, 3 -> 4, 1 -> 5.
Approach: Below is the approach to solve the problem:
The approach used in this code is Union-Find, also known as Disjoint Set Union (DSU). Let's consider that there was no extra edge in the directed graph, then in the graph there would be a root node (no parent) and all the other nodes will have only one parent. Now, adding an extra edge can lead to two cases:
- Connect a node to the root, so every node will have exactly one parent, or
- Connect other nodes such that exactly one of the nodes will have two parents
Explore both the cases to find the answer.
Steps to solve the problem:
Below is the implementation of the above approach:
The redundant directed connection is: [4, 1]
Time complexity: O(N), where N is the number of nodes.
Auxiliary Space: O(N)