VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-of-simple-graph-with-n-vertices-and-m-edges/

⇱ Number of Simple Graph with N Vertices and M Edges - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of Simple Graph with N Vertices and M Edges

Last Updated : 15 Sep, 2022

Given two integers N and M, the task is to count the number of simple undirected graphs that can be drawn with N vertices and M edges. A simple graph is a graph that does not contain multiple edges and self-loops.

Examples: 

Input: N = 3, M = 1 
Output:
The 3 graphs are {1-2, 3}, {2-3, 1}, {1-3, 2}.

Input: N = 5, M = 1 
Output: 10 

Approach: The N vertices are numbered from 1 to N. As there are no self-loops or multiple edges, the edge must be present between two different vertices. So the number of ways we can choose two different vertices is NC2 which is equal to (N * (N - 1)) / 2. Assume it P

Now M edges must be used with these pairs of vertices, so the number of ways to choose M pairs of vertices between P pairs will be PCM

If P < M then the answer will be 0 as the extra edges can not be left alone.

Below is the implementation of the above approach: 


Output
10

Complexity Analysis:

  • Time Complexity: O(M), where M is the number of edges.
  • Space Complexity: O(1), since no extra space has been taken.
Comment
Article Tags: