![]() |
VOOZH | about |
You and your Friend are given an undirected graph having 3 types of edges. A graph is called Reachable if starting from any node, you and your friend can reach all other nodes. Print the maximum number of edges that you can remove in order for the graph to remain Reachable. or print -1.
Examples:
Input: graph[type, u, v] = [[3, 1, 2], [3, 2, 3], [1, 1, 3], [1, 2, 4], [1, 1, 2], [2, 3, 4]], n = 4
Output: 2
Explanation: If we remove the two edges [1,1,2] and [1,1,3] Alice and Bob will still be able to traverse the graph. Any additional edge removal, beyond this point will not enable traversal. Hence the maximum number of edges we can remove is two.Input: graph[type, u, v] = [[3, 2, 3], [1, 1, 2], [2, 3, 4]], n = 4
Output: -1
Explanation: In the given graph it is not possible for Alice to reach node 4 from any node and likewise for Bob to reach node 1. Therefore achieving traversal of the graph is impossible.
Approach: To solve the problem follow the below idea:
To solve this problem we utilize the union find data structure. This structure allows us to keep track of components, for each of the three types of edges (1, 2 and 3). Our algorithm proceeds by iterating through the edges in descending order of type. During each iteration we perform union operations. Keep count of the edges. The final result is obtained by subtracting the count of used edges from the number of edges, which represents the removal required to satisfy the disjoint set condition.
To solve the problem follow the below steps:
Below is the C++ implementation of above approach:
Result: 2
Time Complexity: O(E * α(V))Where E is the number of edges (E), and the inverse Ackermann function (α) and V is the number of nodes (V). It can be considered constant.
Auxiliary Space: O(V) where is the number of nodes (V).