Count the Number of Complete Components - Problem

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.

Input & Output

Example 1 — Mixed Components
$ Input: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]
Output: 3
💡 Note: Component {0,1,2} has 3 vertices and 3 edges, needs 3×2/2=3 edges ✓. Component {3,4} has 2 vertices and 1 edge, needs 2×1/2=1 edge ✓. Component {5} is single vertex ✓. Total: 3 complete components.
Example 2 — No Edges
$ Input: n = 4, edges = []
Output: 4
💡 Note: No edges means 4 isolated vertices: {0}, {1}, {2}, {3}. Each single vertex forms a complete component by definition.
Example 3 — Incomplete Triangle
$ Input: n = 3, edges = [[0,1],[1,2]]
Output: 0
💡 Note: Component {0,1,2} has 3 vertices but only 2 edges. For completeness, needs 3×2/2=3 edges. Missing edge (0,2), so not complete.

Constraints

  • 1 ≤ n ≤ 50
  • 0 ≤ edges.length ≤ n × (n - 1) / 2
  • edges[i].length == 2
  • 0 ≤ ai, bi ≤ n - 1
  • ai ≠ bi
  • There are no repeated edges.

Visualization

Tap to expand
Count the Number of Complete Components INPUT Graph with n=6 vertices 0 1 2 3 4 5 n = 6 edges = [ [0,1], [0,2], [1,2], [3,4] ] ALGORITHM STEPS 1 Build Adjacency List Create graph representation 2 DFS Traversal Find connected components 3 Count Vertices/Edges For each component 4 Check Completeness edges = v*(v-1)/2 ? Completeness Check: Comp 1: v=3, e=3 3=3*(3-1)/2 OK Comp 2: v=2, e=1 1=2*(2-1)/2 OK Comp 3: v=1, e=0 0=1*(1-1)/2 OK All 3 components complete! FINAL RESULT Complete Components Found: Component 1: {0,1,2} Triangle - 3 vertices, 3 edges COMPLETE - OK Component 2: {3,4} Edge - 2 vertices, 1 edge COMPLETE - OK Component 3: {5} Isolated - 1 vertex, 0 edges COMPLETE - OK Output: 3 Key Insight: A complete component with V vertices must have exactly V*(V-1)/2 edges. Use DFS to find all connected components, count vertices and edges in each, then verify the completeness formula for each component. TutorialsPoint - Count the Number of Complete Components | DFS Approach
Asked in
Meta 8 Google 6 Amazon 4
18.9K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen