Check if every vertex triplet in graph contains two vertices connected to third vertex
Given an undirected graph with N vertices and K edges, the task is to check if for every combination of three vertices in the graph, there exists two vertices which are connected to third vertex. In other words, for every vertex triplet (a, b, c), if there exists a path between a and c, then there should also exist a path between b and c.
Input: N = 4, K = 3
Edges: 1 -> 2, 2 -> 3, 3 -> 4
Since the whole graph is connected, the above condition will always be valid.
Input: N = 5 and K = 3
Edges: 1 -> 3, 3 -> 4, 2 -> 5.
If we consider the triplet (1, 2, 3) then there is a path between vertices 1 and 3 but there is no path between vertices 2 and 3.
Approach: Follow the steps below to solve the problem –
- Traverse the graph by DFS Traversal technique from any component and maintain two variables to store the component minimum and component maximum.
- Store every component maximum and minimum in a vector.
- Now, if any two components have an intersection in their minimum and maximum values interval, then there will exist a valid (a < b < c) triplet. Hence, both of the components should be connected. Otherwise, the graph is not valid.
Below is the implementation of the above approach
Time Complexity: O(N + E)
Auxiliary Space: O(N)