VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-for-transitive-property-in-a-given-undirected-graph/

⇱ Check for transitive property in a given Undirected Graph - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for transitive property in a given Undirected Graph

Last Updated : 23 Jul, 2025

Given an undirected graph G with vertices numbered in the range [1, N] and an array Edges[][] consisting of M edges, the task is to check if all triplets of the undirected graph satisfies the transitive property or not. If found to be true, then print "YES". Otherwise, print "NO".

Transitive property of an undirected graph states that:
If vertex X is connected to vertex Y, vertex Y is connected to vertex Z, then vertex X must be connected to the vertex Z.

Examples:

Input: N = 4, M = 3 Edges[] = {{1, 3}, {3, 4}, {1, 4}}
Output: YES 
Explanation:

👁 Image

Input : N = 4, M = 4, Edges[] = {{3, 1}, {2, 3}, {3, 4}, {1, 2}}
Output: NO 
Explanation:

👁 Image

Naive Approach: The simplest approach to solve the above problem is to traverse over every triplet of vertices (i, j, k), and for each such triplet, check if there is an edge between vertices j and k if i and j, and i and k are directly connected by an edge with the help of an adjacency matrix. 

Time Complexity: O(N3)
Auxiliary Space: O(N2)

Efficient Approach: The idea is to find all the connected components present in the graph. Finally, check if all the connected components of the graph are a complete graph or not. If found to be true, then print "YES". Otherwise, print "NO". Follow the steps below to solve the problem:

  • Represent the graph, G in the form of adjacency list.
  • Find all the connected components of the graph and check if the connected component is a complete graph or not by performing the following operations: 
    • Find total count of vertices in the current connected graph say, X.
    • If all the vertices of the connected component are not connected to X - 1 vertices, then print "NO".
  • Finally, check if all the connected components are a complete graph or not. IF found to be true, then print "YES".

Below is the implementation of the above approach:


Output: 
YES

 

Time Complexity: O(N + M)
Auxiliary Space: O(N2)

Comment