Count the Number of Complete Components Problem
Description
LeetCode Problem 2685.
You are given an integer n. There is an undirected graph with n vertices, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [a_i, b_i] denotes that there exists an undirected edge connecting vertices a_i and b_i.
Return the number of complete connected components of the graph.
A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.
A connected component is said to be complete if there exists an edge between every pair of its vertices.
Example 1:

Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
Output: 3
Explanation: From the picture above, one can see that all of the components of this graph are complete.
Example 2:

Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]]
Output: 1
Explanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.
Constraints:
1 <= n <= 500 <= edges.length <= n * (n - 1) / 2edges[i].length == 20 <= a_i, b_i <= n - 1a_i != b_i- There are no repeated edges.
Solution
Approach: DFS with vertex and edge counts
A component with x vertices is complete exactly when every vertex has x - 1 neighbours, that is, when the sum of all degrees in it equals x(x - 1).
Run a DFS from every unvisited vertex. While walking the component, count its vertices x and add up the degrees of its vertices to get y (each edge is counted twice). The component is complete when x * (x - 1) == y.
Complexity: time O(n + m), space O(n + m), where m is the number of edges.
from collections import defaultdict
class Solution:
def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> (int, int):
vis[i] = True
x, y = 1, len(g[i])
for j in g[i]:
if not vis[j]:
a, b = dfs(j)
x += a
y += b
return x, y
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
vis = [False] * n
ans = 0
for i in range(n):
if not vis[i]:
a, b = dfs(i)
ans += a * (a - 1) == b
return ans