Given an adjacency list representation undirected graph. Write a function to count the number of edges in the undirected graph.
Expected time complexity : O(V)
Idea is based on Handshaking Lemma. Handshaking lemma is about undirected graph. In every finite undirected graph number of vertices with odd degree is always even. The handshaking lemma is a consequence of the degree sum formula (also sometimes called the handshaking lemma)
So we traverse all vertices, compute sum of sizes of their adjacency lists, and finally returns sum/2. Below c++ implementation of above idea
Time Complexity : O(V)
This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Maximum number of edges among all connected components of an undirected graph
- Minimum number of edges between two vertices of a Graph
- Number of Triangles in an Undirected Graph
- Program to find total number of edges in a Complete Graph
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph
- Number of single cycle components in an undirected graph
- Undirected graph splitting and its application for number pairs
- All vertex pairs connected with exactly k edges in a graph
- Clone an Undirected Graph
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Shortest path with exactly k edges in a directed and weighted graph
- Largest subset of Graph vertices with edges of 2 or more colors
- Find k-cores of an undirected graph
- Detect cycle in an undirected graph
- Connected Components in an undirected graph