Count the Number of Complete Components (LeetCode 2685): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Union Find
Graph

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

  1. Build adjacency lists from the edges.
  2. For each unseen vertex, start a stack-based DFS that marks every vertex of its component.
  3. While popping, count the vertices nodes and add each vertex's degree to degrees.
  4. After the stack empties, the component is complete if degrees == nodes * (nodes - 1); if so, increase the count.
  5. Return the count.

Step-by-step example

n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
  1. Degrees: 0, 1 and 2 have degree 2; 3 and 4 have degree 1; 5 has degree 0.
  2. Start at 0: the DFS reaches 0, 2, 1. nodes = 3, degrees = 6 = 3 x 2, so it is complete. count = 1.
  3. Start at 3: the DFS reaches 3 and 4. nodes = 2, degrees = 2 = 2 x 1, complete. count = 2.
  4. Start at 5: nodes = 1, degrees = 0 = 1 x 0, complete. count = 3.
  5. 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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

Each vertex is pushed and popped once and each edge is looked at twice, once from each end.

Space

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.