Count the Number of Complete Components (LeetCode 2685): Solution and Explanation
Given an undirected graph on n vertices, count the connected components in which every pair of vertices is joined by an edge.
Intuition
A component with k vertices is complete when it holds every possible edge, which is k(k-1)/2 edges. So the question per component is just: how many vertices and how many edges does it have?
Counting edges directly needs care to avoid counting each one twice. Summing the degrees of the component's vertices is easier: every edge adds exactly 2 to that sum. A complete component therefore has a degree sum of exactly k(k-1).
One DFS per component collects both numbers at once: each popped vertex adds 1 to k and its degree to the sum.
Approach: DFS per component with a degree-sum check
- Build adjacency lists from the edges.
- For each unseen vertex, start a stack-based DFS that marks every vertex of its component.
- While popping, count the vertices
nodesand add each vertex's degree todegrees. - After the stack empties, the component is complete if
degrees == nodes * (nodes - 1); if so, increase the count. - Return the count.
Step-by-step example
n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
- Degrees: 0, 1 and 2 have degree 2; 3 and 4 have degree 1; 5 has degree 0.
- Start at 0: the DFS reaches 0, 2, 1. nodes = 3, degrees = 6 = 3 x 2, so it is complete. count = 1.
- Start at 3: the DFS reaches 3 and 4. nodes = 2, degrees = 2 = 2 x 1, complete. count = 2.
- Start at 5: nodes = 1, degrees = 0 = 1 x 0, complete. count = 3.
- Return 3.
Code: Python, Java, C++
1class Solution:
2 def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
3 adj = [[] for _ in range(n)]
4 for a, b in edges:
5 adj[a].append(b)
6 adj[b].append(a)
7 seen = [False] * n
8 count = 0
9 for start in range(n):
10 if seen[start]:
11 continue
12 seen[start] = True
13 stack = [start]
14 nodes = 0
15 degrees = 0
16 while stack:
17 u = stack.pop()
18 nodes += 1
19 degrees += len(adj[u])
20 for v in adj[u]:
21 if not seen[v]:
22 seen[v] = True
23 stack.append(v)
24 if degrees == nodes * (nodes - 1):
25 count += 1
26 return count1class Solution {
2 public int countCompleteComponents(int n, int[][] edges) {
3 List<List<Integer>> adj = new ArrayList<>();
4 for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
5 for (int[] e : edges) {
6 adj.get(e[0]).add(e[1]);
7 adj.get(e[1]).add(e[0]);
8 }
9 boolean[] seen = new boolean[n];
10 int count = 0;
11 for (int start = 0; start < n; start++) {
12 if (seen[start]) continue;
13 seen[start] = true;
14 Deque<Integer> stack = new ArrayDeque<>();
15 stack.push(start);
16 int nodes = 0, degrees = 0;
17 while (!stack.isEmpty()) {
18 int u = stack.pop();
19 nodes++;
20 degrees += adj.get(u).size();
21 for (int v : adj.get(u)) {
22 if (!seen[v]) {
23 seen[v] = true;
24 stack.push(v);
25 }
26 }
27 }
28 if (degrees == nodes * (nodes - 1)) {
29 count++;
30 }
31 }
32 return count;
33 }
34}1class Solution {
2public:
3 int countCompleteComponents(int n, vector<vector<int>>& edges) {
4 vector<vector<int>> adj(n);
5 for (auto& e : edges) {
6 adj[e[0]].push_back(e[1]);
7 adj[e[1]].push_back(e[0]);
8 }
9 vector<bool> seen(n, false);
10 int count = 0;
11 for (int start = 0; start < n; start++) {
12 if (seen[start]) continue;
13 seen[start] = true;
14 vector<int> stack = {start};
15 int nodes = 0, degrees = 0;
16 while (!stack.empty()) {
17 int u = stack.back();
18 stack.pop_back();
19 nodes++;
20 degrees += adj[u].size();
21 for (int v : adj[u]) {
22 if (!seen[v]) {
23 seen[v] = true;
24 stack.push_back(v);
25 }
26 }
27 }
28 if (degrees == nodes * (nodes - 1)) {
29 count++;
30 }
31 }
32 return count;
33 }
34};Time and space complexity
O(n + m)
Each vertex is pushed and popped once and each edge is looked at twice, once from each end.
O(n + m)
The adjacency lists store every edge twice, and the seen array and stack hold up to n vertices.
Other approaches
Union-find (time O((n + m) * a(n)), space O(n))
Union the endpoints of every edge, then for each root count its vertices and its edges (attribute each edge to the root of one endpoint). A root with k vertices and k(k-1)/2 edges is complete.
Check every pair (time O(n^2), space O(n^2))
After finding a component, test each pair of its vertices for an edge with an adjacency matrix. Fine for n up to 50, but quadratic in the component size.
Common mistakes
- Comparing the degree sum with k(k-1)/2 instead of k(k-1). The degree sum counts each edge twice.
- Forgetting isolated vertices. A single vertex with no edges is a complete component.
- Marking a vertex as seen only when it is popped. It can then be pushed several times and counted more than once.
- Checking only that every vertex has degree k - 1 without first restricting to the component. That works, but only after the component is known.
Frequently asked questions
Why is the degree sum exactly k(k-1) for a complete component?
Each of the k vertices is joined to the other k - 1, so each has degree k - 1. Adding k copies of k - 1 gives k(k-1).
Can the degree sum ever be larger than k(k-1)?
No. There are no repeated edges or self-loops, so a vertex has at most k - 1 neighbors inside its component, and it has none outside.
Does a single vertex count?
Yes. With k = 1 there are no pairs to connect, and the degree sum 0 equals 1 x 0.
Does the DFS order matter?
No. Any traversal that visits each vertex of the component once gives the same vertex count and degree sum.