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 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 firstname.lastname@example.org. 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.
- Breadth First Search or BFS for a Graph
- Find if there is a path between two vertices in a directed graph
- Depth First Search or DFS for a Graph
- Detect Cycle in a Directed Graph
- Find the number of islands | Set 1 (Using DFS)
- Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
- Graph and its representations
- Transitive closure of a graph
- Check whether a given graph is Bipartite or not
- Shortest Path in Directed Acyclic Graph
- Bridges in a graph
- Articulation Points (or Cut Vertices) in a Graph
- Biconnected graph
- Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
- Eulerian path and circuit for undirected graph