I have been solving some questions based on graphs and cycles. I have decided to frame a question on cycles in Graphs.

Given an undirected graph having N number of vertices (numbered from 1 to N) and E edges. How to find the vertices that form 3 length cycles. Here the 3 length means 3 edges in the cycle path.

First line contains N and E

Following E lines contains undirected edges.

Example:

6 8

1 3

2 3

2 4

2 5

3 5

4 5

4 6

5 6

The above graph has 6 vertices and 8 edges.

The nodes that form 3 length cycles are:

2 3 4 5 6

because {2,3,5}, {2,4,5} and {4,5,6} form cycles.

I am able to do this in the Quadratic time.

My Approach:

dfs and check the common nodes between the vertices adjacency lists(can do this using a map of element and set of adjacency list elements). Add all of them to the set.

Finally print the set.

Could anyone suggest any approach to do this in O(n) or O(nlogn).

Any other approaches are always welcome

Thank you