Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 22, 2025 21:26
Show Gist options
  • Save Ifihan/ff9fe566b0c9a07096fc3f29b681667b to your computer and use it in GitHub Desktop.
Save Ifihan/ff9fe566b0c9a07096fc3f29b681667b to your computer and use it in GitHub Desktop.
Count the Number of Complete Components

Question

Approach

I perform BFS on each unvisited node to gather all nodes in a connected component. I then count the number of nodes and edges in that component. A complete component of size k must have exactly k*(k-1)/2 edges.

Implementation

class Solution:
    def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
        graph = defaultdict(set)
        for u, v in edges:
            graph[u].add(v)
            graph[v].add(u)

        visited = [False] * n
        complete_components = 0

        for i in range(n):
            if not visited[i]:
                queue = deque([i])
                visited[i] = True
                nodes = [i]
                edge_count = 0

                while queue:
                    node = queue.popleft()
                    for neighbor in graph[node]:
                        edge_count += 1
                        if not visited[neighbor]:
                            visited[neighbor] = True
                            queue.append(neighbor)
                            nodes.append(neighbor)

                edge_count //= 2
                size = len(nodes)
                if edge_count == size * (size - 1) // 2:
                    complete_components += 1

        return complete_components

Complexities

  • Time: O(n + e)
  • Space: O(n + e)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment