VOOZH about

URL: https://www.geeksforgeeks.org/dsa/extra-edge-in-a-directed-rooted-tree/

⇱ Extra Edge in a Directed Rooted Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Extra Edge in a Directed Rooted Tree

Last Updated : 23 Jul, 2025

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:

  • Check if there is a node with two parents by iterating over the edges of the graph.
    • If we encounter a node with two parents, record the first edge to the node as edge1 and the second edge to the node as edge2
  • Disconnect the edge2 to create a tree structure without the second parent.
  • Initialize an ancestor array where each node initially points to itself.
  • Iterate over the edges of the graph, for every edge:
    • Find the root ancestor (pu) of the source node (u).
    • If the root ancestor of the source node (pu) is the same as the target node (v), it indicates a cycle in the graph. In this case, if edge1 is empty, return the current edge as the extra edge. Else, if edge1 is not empty, return edge1 as the extra edge.
    • If there's no cycle, union the ancestors of u and v by making the ancestor of v point to the root ancestor of u.
  • Finally, return edge2 as the extra edge, which was disconnected earlier to create a tree structure.

Below is the implementation of the above approach:


Output
The redundant directed connection is: [4, 1]

Time complexity: O(N), where N is the number of nodes.
Auxiliary Space: O(N)

Comment