Count of connected components in given graph after removal of given Q vertices
Last Updated : 23 Jul, 2025
Given an undirected graph g, the task is to find the number of coalitions formed in it after the removal of Q vertices and maximum vertices among all these connected components.
A coalition is defined as the number of connected components left after removal of Q vertices i.e vertices being removed from the graph are not considered as part of the coalition.
If we remove vertices 3 from the graph then their corresponding edges {{0, 3}, {3, 6}, {3, 2}} will also be get removed from the graph and the number of the connected components excluding Q (removed vertices) are {0}. {1, 5, 6} and {2, 4} with maximum coalition of {1, 5, 6} as 3.
Output: 1 4 Explanation: When vertex 1 and 2 is removed from the given graph the connected component excluding Q is {0, 3, 4, 5} with maximum coalition of {0, 3, 4, 5} as 4.
Approach: The approach to solve this problem based on following idea
The idea here is, if we remove all unnecessary edges that connects with the vertex mentioned in the query, then the problem will break down to find the number of connected component in undirected graph.
Based on above idea follow the steps below to implement this approach:
We can use the multimap to store edges between the vertices.
We remove all edges that are connected with the vertices (because we assume that we will have to delete all the vertices from the Query then, their corresponding edges should also be get remove that are connected with the vertices)
Use a variable count to store the number of connected components, cnt to keep count of number of vertices of the component we are traversing and maxLen to store maximum vertices among all components ( maximum of cnt ).
Calculate coalitions = count ( number of connected components ) - size of query ( number of vertices removed)
Below is the implementation of the above approach:
C++14
#include<bits/stdc++.h>usingnamespacestd;intmaxLen=0;intcnt;classGraph{intV;list<int>*adj;multimap<int,int>adj2;voidDFSUtil(intv,boolvisited[]);public:Graph(intV);voidaddEdges();voidremoveEdges(intV,intEdges[][2],intE,intqueries[],intQ);intNumberOfconnectedComponents();};// function to find the number of connected// component in undirected graphintGraph::NumberOfconnectedComponents(){bool*visited=newbool[V];intcount=0;for(intv=0;v<V;v++)visited[v]=false;for(intv=0;v<V;v++){if(visited[v]==false){cnt=0;DFSUtil(v,visited);count+=1;}}returncount;}voidGraph::DFSUtil(intv,boolvisited[]){visited[v]=true;cnt++;list<int>::iteratori;for(i=adj[v].begin();i!=adj[v].end();++i)if(!visited[*i]){DFSUtil(*i,visited);}maxLen=max(maxLen,cnt);}Graph::Graph(intV){this->V=V;adj=newlist<int>[V];}// add Edges in the graphvoidGraph::addEdges(){for(autox:adj2){adj[x.first].push_back(x.second);adj[x.second].push_back(x.first);}}// function to remove all the edges that are// connected with verticesvoidGraph::removeEdges(intV,intEdges[][2],intE,intqueries[],intQ){multimap<int,int>adj3;for(inti=0;i<E;i++)adj3.insert({Edges[i][0],Edges[i][1]});for(inti=0;i<Q;i++){autoit1=adj3.lower_bound(queries[i]);autoit2=adj3.upper_bound(queries[i]);adj3.erase(it1,it2);}for(autoit=adj3.begin();it!=adj3.end();it++){adj2.insert({it->second,it->first});}for(inti=0;i<Q;i++){autoit1=adj2.lower_bound(queries[i]);autoit2=adj2.upper_bound(queries[i]);adj2.erase(it1,it2);}}// Driver codeintmain(){intV=7,E=6;Graphg(V);intEdges[][2]={{0,3},{1,5},{3,6},{3,2},{2,4},{5,6}};intQ=1;intqueries[]={3};// remove all the edges that are connected with// vertices given in the queriesg.removeEdges(V,Edges,E,queries,Q);g.addEdges();cout<<g.NumberOfconnectedComponents()-Q;cout<<" "<<maxLen;return0;}
Java
// Java code addition for the above approachimportjava.io.*;importjava.util.*;classGraph{privateintV;privateList<Integer>[]adj;privateTreeMap<Integer,Integer>adj2;publicintmaxLen=0;publicintcnt;publicGraph(intV){this.V=V;adj=newList[V];for(inti=0;i<V;i++)adj[i]=newArrayList<>();adj2=newTreeMap<>();}// add Edges in the graphpublicvoidaddEdges(){for(Map.Entry<Integer,Integer>entry:adj2.entrySet()){intkey=entry.getKey();intvalue=entry.getValue();adj[key].add(value);adj[value].add(key);}}// Function to remove all the edges that are connected// with verticespublicvoidremoveEdges(intV,int[][]Edges,intE,int[]queries,intQ){TreeMap<Integer,Integer>adj3=newTreeMap<>();for(inti=0;i<E;i++)adj3.put(Edges[i][0],Edges[i][1]);for(inti=0;i<Q;i++)adj3.remove(queries[i]);for(Map.Entry<Integer,Integer>it:adj3.entrySet())adj2.put(it.getValue(),it.getKey());for(inti=0;i<Q;i++)adj2.remove(queries[i]);}// Function to find the number of connected component in// undirected graphpublicintnumberOfConnectedComponents(){boolean[]visited=newboolean[V];intcount=0;for(intv=0;v<V;v++)visited[v]=false;for(intv=0;v<V;v++){if(!visited[v]){cnt=0;DFSUtil(v,visited);count+=1;}}returncount;}publicvoidDFSUtil(intv,boolean[]visited){visited[v]=true;cnt++;for(inti:adj[v]){if(!visited[i])DFSUtil(i,visited);}maxLen=Math.max(maxLen,cnt);}}classGFG{publicstaticvoidmain(String[]args){intV=7,E=6;Graphg=newGraph(V);int[][]Edges={{0,3},{1,5},{3,6},{3,2},{2,4},{5,6}};intQ=1;int[]queries={3};// remove all the edges that are connected with// vertices given in the queriesg.removeEdges(V,Edges,E,queries,Q);g.addEdges();System.out.println(g.numberOfConnectedComponents()-Q+" "+g.maxLen);}}// This code is contributed by karthik
Python3
fromcollectionsimportdefaultdictclassGraph:def__init__(self,V):self.V=Vself.adj=defaultdict(list)self.adj2={}#add Edges in the graphdefadd_edges(self):forxinself.adj2:self.adj[x[0]].append(x[1])self.adj[x[1]].append(x[0])defremove_edges(self,V,Edges,E,queries,Q):adj3={}foriinrange(E):adj3[Edges[i][0]]=Edges[i][1]foriinrange(Q):adj3.pop(queries[i],None)foritinadj3.items():self.adj2[it[1],it[0]]=Trueforiinrange(Q):self.adj2.pop(queries[i],None)defnumber_of_connected_components(self):visited=[False]*self.Vcount=0max_len=0defDFS_util(v,visited,cnt):nonlocalmax_lenvisited[v]=Truecnt[0]+=1foriinself.adj[v]:ifnotvisited[i]:DFS_util(i,visited,cnt)max_len=max(max_len,cnt[0])forvinrange(self.V):ifnotvisited[v]:cnt=[0]DFS_util(v,visited,cnt)count+=1returncount,max_len#Driver codeV=7E=6g=Graph(V)Edges=[[0,3],[1,5],[3,6],[3,2],[2,4],[5,6]]Q=1queries=[3]# remove all the edges that are connected with vertices given in the queriesg.remove_edges(V,Edges,E,queries,Q)g.add_edges()result=g.number_of_connected_components()print(result[0],result[1])
C#
//C# code for the above approachusingSystem;usingSystem.Collections.Generic;publicclassGraph{privateintV;privateList<int>[]adj;privateSortedDictionary<int,int>adj2;publicGraph(intV){this.V=V;adj=newList<int>[V];for(inti=0;i<V;i++)adj[i]=newList<int>();adj2=newSortedDictionary<int,int>();}publicvoidaddEdges(){foreach(KeyValuePair<int,int>xinadj2){adj[x.Key].Add(x.Value);adj[x.Value].Add(x.Key);}}// function to remove all the edges that are// connected with verticespublicvoidremoveEdges(intV,int[,]Edges,intE,int[]queries,intQ){SortedDictionary<int,int>adj3=newSortedDictionary<int,int>();for(inti=0;i<E;i++)adj3[Edges[i,0]]=Edges[i,1];for(inti=0;i<Q;i++)adj3.Remove(queries[i]);foreach(KeyValuePair<int,int>itinadj3)adj2[it.Value]=it.Key;for(inti=0;i<Q;i++)adj2.Remove(queries[i]);}publicintNumberOfconnectedComponents(){bool[]visited=newbool[V];intcount=0;for(intv=0;v<V;v++)visited[v]=false;for(intv=0;v<V;v++){if(!visited[v]){cnt=0;DFSUtil(v,visited);count+=1;}}returncount;}publicintmaxLen=0;publicintcnt;publicvoidDFSUtil(intv,bool[]visited){visited[v]=true;cnt++;foreach(intiinadj[v]){if(!visited[i])DFSUtil(i,visited);}maxLen=Math.Max(maxLen,cnt);}}publicclassProgram{// Driver codepublicstaticvoidMain(){intV=7,E=6;Graphg=newGraph(V);int[,]Edges={{0,3},{1,5},{3,6},{3,2},{2,4},{5,6}};intQ=1;int[]queries={3};// remove all the edges that are connected with// vertices given in the queriesg.removeEdges(V,Edges,E,queries,Q);g.addEdges();Console.WriteLine(g.NumberOfconnectedComponents()-Q+" "+g.maxLen);}}
JavaScript
// JavaScript code for the above approachclassGraph{constructor(V){this.V=V;this.adj=newArray(V);for(leti=0;i<V;i++){this.adj[i]=[];}this.adj2=newMap();this.maxLen=0;this.cnt=0;}// add Edges in the graphaddEdges(){for(let[key,value]ofthis.adj2){this.adj[key].push(value);this.adj[value].push(key);}}// Function to remove all the edges that are connected with verticesremoveEdges(V,Edges,E,queries,Q){letadj3=newMap();for(leti=0;i<E;i++){adj3.set(Edges[i][0],Edges[i][1]);}for(leti=0;i<Q;i++){adj3.delete(queries[i]);}for(let[key,value]ofadj3){this.adj2.set(value,key);}for(leti=0;i<Q;i++){this.adj2.delete(queries[i]);}}// Function to find the number of connected component in undirected graphnumberOfConnectedComponents(){letvisited=newArray(this.V).fill(false);letcount=0;for(letv=0;v<this.V;v++){if(!visited[v]){this.cnt=0;this.DFSUtil(v,visited);count+=1;}}returncount;}DFSUtil(v,visited){visited[v]=true;this.cnt++;for(letiofthis.adj[v]){if(!visited[i]){this.DFSUtil(i,visited);}}this.maxLen=Math.max(this.maxLen,this.cnt);}}letV=7,E=6;letg=newGraph(V);letEdges=[[0,3],[1,5],[3,6],[3,2],[2,4],[5,6]];letQ=1;letqueries=[3];// remove all the given edges that are connected with vertices// given in the queriesg.removeEdges(V,Edges,E,queries,Q);g.addEdges();console.log(g.numberOfConnectedComponents()-Q+" "+g.maxLen);// This code is contributed by sankar.
Output
3 3
Time complexity: O(V + E*log(E)), where V is the number of vertices and E is the number of edges in the graph. Auxiliary Space: O(V), since an extra visited array of size V is required.