#2685
Count the Number of Complete Components
MediumDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph Traversal (DFS/BFS)Union-Find (for connected components)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + e) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + e)Space O(n)
The optimal approach uses a graph traversal technique (DFS or BFS) to efficiently explore connected components and check their completeness in a single pass. This reduces the need to repeatedly check edges and vertices, making it faster.
⚙️
Algorithm
5 steps- 1Step 1: Create an adjacency list from the edges.
- 2Step 2: Use DFS or BFS to find all connected components.
- 3Step 3: For each connected component, count the number of vertices and edges.
- 4Step 4: Check if the number of edges equals (vertices * (vertices - 1)) / 2 to determine if it's complete.
- 5Step 5: Count and return the number of complete components.
solution.py34 lines
1# Full working Python code
2from collections import defaultdict
3
4def countCompleteComponents(n, edges):
5 graph = defaultdict(list)
6 for a, b in edges:
7 graph[a].append(b)
8 graph[b].append(a)
9
10 visited = set()
11 complete_count = 0
12
13 def dfs(node):
14 stack = [node]
15 component = []
16 while stack:
17 curr = stack.pop()
18 if curr not in visited:
19 visited.add(curr)
20 component.append(curr)
21 for neighbor in graph[curr]:
22 if neighbor not in visited:
23 stack.append(neighbor)
24 return component
25
26 for i in range(n):
27 if i not in visited:
28 component = dfs(i)
29 edges_count = sum(len(graph[v]) for v in component) // 2
30 if edges_count == (len(component) * (len(component) - 1)) // 2:
31 complete_count += 1
32
33 return complete_count
34ℹ
Complexity note: This complexity is efficient because we traverse each vertex and edge only once, leading to a linear relationship with respect to the number of vertices and edges.
- 1Understanding the definition of connected components is crucial for solving graph problems.
- 2A complete component must have edges between every pair of vertices, which can be checked using the formula for complete graphs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.