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] = [ai, bi] denotes that there exists an undirected edge connecting vertices ai and bi.
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 <= ai, bi <= n - 1ai != biThis approach involves sorting the array and then finding the target element based on the problem's requirement. Sorting simplifies many search operations by arranging the elements in a predetermined order.
This C program sorts an array and then searches for a target element. The qsort function is used for sorting, providing a fast O(n log n) solution. After sorting, a linear search is performed to find the target element, which can be optimized further.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting
Space Complexity: O(1) as it sorts in place
This approach leverages a hash map for quick look-up times. By storing elements in a hash map with their indices, we can reduce the time complexity for look-up operations significantly.
This C implementation uses a simple hash map to find elements quickly. The hash map provides an average time complexity of O(1) for both insertion and lookup, making this approach efficient for large inputs.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) for building the map
Space Complexity: O(n) for map storage
| Approach | Complexity |
|---|---|
| Approach 1: Using Sorting | Time Complexity: O(n log n) due to sorting |
| Approach 2: Using a Hash Map | Time Complexity: O(n) for building the map |
Number of Connected Components in an Undirected Graph - Union Find - Leetcode 323 - Python • NeetCode • 205,472 views views
Watch 9 more video solutions →Practice Count the Number of Complete Components with our built-in code editor and test cases.
Practice on FleetCode