![]() |
VOOZH | about |
Given an undirected graph with N nodes, M edges given by array edges[][2] and permutation array A[] of size N which indicates the order in which each and every node of graph will be removed. The task is to find if graph is connected or not after removal of ith node sequential from given array A[]. Graph is connected if it is possible to traverse from any node to any other node. Print "YES" if graph is connected else print "NO".
Removal of node is permanent from the given undirected graph.
Examples:
Input: N = 4, edges[][2] = { {1, 2}, {2, 3}, {3, 4} }, A[] = {3, 4, 1, 2}
Output: NO YES YES YES
Explanation:
- Removing node A[1] = 3, after removal as there is no path to travel between 1 and 4 hence "NO" is answer.
- Removing node A[2] = 4, after removal graph becomes connected hence "YES" is answer
- Removing node A[3] = 1, after removal graph is still connected since it has only one node left hence "YES" is answer
- Removing node A[4] = 2, after removal graph has no nodes hence "YES" is answer
Input: N = 5, edges[][2] = { {1, 2}, {1, 3}, {3, 5}, {2, 5}, {5, 4} }, A[] = {3, 5, 2, 4, 1}
Output: YES NO NO YES YES
Explanation:
- Removing node A[1] = 3, after removal as whole graph is still connected hence "YES" is answer
- Removing node A[2] = 5, after removal as there is no path to travel between 1 and 4 hence "NO" is answer
- Removing node A[3] = 2, after removal as there is still no path to travel between 1 and 4 hence "NO" is answer
- Removing node A[4] = 4, after removal as there is only one node left hence "YES" is answer
- Removing node A[5] = 1, after removal graph has no nodes hence "YES" is answer.
Approach: The problem can be solved using the following approach:
Disjoint Set can be used to solve this problem. Rather than deleting from first node to last node and run a DFS for every node to check whether the graph is connected, we can start from the last node and keep inserting the nodes and keeping the count of nodes in each connected component.
Rather than deleting in A[0] -> A[1] -> A[2] -> ...... ->A[N - 1] this order
Let's insert in A[N - 1] -> A[N - 2] -> A[N - 3] ....... -> A[0] this order
Insertion operation will be made using union() function of DSU and before each insertion we will check whether given graph is connected or not by finding component size in which the current node belongs. If the size is equal to number of elements inserted, then graph is connected otherwise it is disconnected.
Below are the steps for the above approach:
Below is the implementation of the above approach:
YES NO NO YES YES
Time Complexity: O(N), where N is the number of nodes in the input graph.
Auxiliary Space: O(N)