I have an undirected unweighted graph G = (V, E) and a randomly chosen subset S of its vertices. I want to check whether the vertices in S are mutually adjacent (i.e. form a complete subgraph/a clique).
I have the following algorithm (pseudo-code):
foreach vertex in S {
// Check that the vertex has enough edges
if (vertex.edges.count < S.size - 1)
return false;
// Check that there is an edge to each vertex in S
foreach vertex2 in S {
if (!vertex.hasEdgeTo(vertex2))
return false;
}
}
return true;
The problem is that this algorithm’s worst-case performance is O(|V|2) (in case when the subset S contains all the vertices of a complete graph).
My question is: is there a faster algorithm that runs with a better big O worst-case complexity?
Assuming that you can check whether two vertices are incident in
O(1), your algorithm hasO(|V|²) = O(|E|)time complexity in the worst case. I don’t think you can do better thanO(|E|), since you should really check all the edges of the subgraph.