Count the Number of Complete Components - Problem
You're given an undirected graph with n vertices numbered from 0 to n-1, along with a list of edges connecting these vertices. Your task is to find how many complete connected components exist in this graph.
Let's break this down:
- A connected component is a group of vertices where you can reach any vertex from any other vertex within the group, but no vertex in the group connects to vertices outside the group.
- A connected component is complete if every pair of vertices within it has a direct edge between them (forming a clique).
Example: If you have vertices [0,1,2] in a component with edges [[0,1], [0,2], [1,2]], this forms a complete component because every vertex connects to every other vertex in the group.
Return the total count of such complete connected components in the graph.
Input & Output
example_1.py โ Python
$
Input:
n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
โบ
Output:
2
๐ก Note:
Component {0,1,2} has 3 vertices and edges between every pair (complete). Component {3,4} has 2 vertices and 1 edge between them (complete). Component {5} is a single vertex (complete by definition).
example_2.py โ Python
$
Input:
n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]]
โบ
Output:
1
๐ก Note:
Component {0,1,2} is complete (triangle). Component {3,4,5} has 3 vertices but only 2 edges - missing edge between 4 and 5, so not complete.
example_3.py โ Python
$
Input:
n = 3, edges = []
โบ
Output:
3
๐ก Note:
Each vertex forms its own component: {0}, {1}, {2}. Single vertex components are complete by definition.
Visualization
Tap to expand
Understanding the Visualization
1
Build Graph
Create adjacency list representation of the undirected graph
2
Find Components
Use DFS to identify all connected components
3
Check Completeness
For each component with k vertices, verify it has k*(k-1)/2 edges
4
Count Results
Return the total number of complete components found
Key Takeaway
๐ฏ Key Insight: Instead of checking every pair of vertices in each component (O(kยฒ)), we can use the mathematical property that complete graphs have exactly k*(k-1)/2 edges, reducing the verification to O(1) per component.
Time & Space Complexity
Time Complexity
O(Vยฒ + E)
O(V + E) for DFS traversal, plus O(Vยฒ) in worst case for checking all pairs in components
โ Linear Growth
Space Complexity
O(V + E)
Space for adjacency list, visited array, and recursion stack
โ Linear Space
Constraints
- 1 โค n โค 50
- 0 โค edges.length โค n * (n - 1) / 2
- edges[i].length == 2
- 0 โค ai, bi โค n - 1
- ai != bi
- No duplicate edges
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code