![]() |
VOOZH | about |
Given an undirected graph of N nodes labelled from 1 to N, the task is to find the minimum labelled node that should be removed from the graph such that the resulting graph has no cycle.
Note: If the initial graph has no cycle, i.e. no node needs to be removed, print -1.
Examples:
Input: N = 5, edges[][] = {{5, 1}, {5, 2}, {1, 2}, {2, 3}, {2, 4}}
Output: 1
Explanation:
If node 1 is removed, the resultant graph has no cycle. Similarly, the cycle can be avoided by removing node 2 also.
Since we have to find the minimum labelled node, the answer is 1.Input: N = 5, edges[][] = {{4, 5}, {4, 1}, {4, 2}, {4, 3}, {5, 1}, {5, 2}}
Output: 4
Naive Approach: The naive approach for this problem would be to remove each vertex individually and check whether the resulting graph has a cycle or not. The time complexity for this approach is quadratic.
Efficient Approach: The idea is to apply depth-first search on the given graph and observing the dfs tree formed.
If there are back edges in the graph, then we need to find the minimum edge. In order to do this, we need to check if the cycle is removed on removing a specific edge from the graph. Therefore, let v be a vertex which we are currently checking. Therefore, the following conditions must be followed by vertex v such that on removing, it would lead to no cycle:
Therefore, the idea is to keep a track of back edges, and an indicator for the number of back edges in the subtree of a node to any of its ancestors. To keep a track of back edges we will use a modified DFS graph colouring algorithm.
In order to check if the subtree v has at-most one back edge to any ancestor of v or not, we implement dfs such that it returns the depth of two highest edges from the subtree of v. We maintain an array where every index 'i' in the array stores if the condition 2 from the above is satisfied by the node 'i' or not. Similarly, two arrays are implemented, one for the child and another for the parent to see if the node v lies on the tree path connecting the endpoints.
Below is the implementation of the above approach:
1
Time Complexity: O(N + M), where N is the number of nodes and M is the number of edges.
Auxiliary Space: O(N + M).