Connected Components

Graphs Theory and traversals Medium

Given a undirected Graph consisting of V vertices numbered from 0 to V-1 and E edges. The ith edge is represented by [ai,bi], denoting a edge between vertex ai and bi. We say two vertices u and v belong to a same component if there is a path from u to v or v to u. Find the number of connected components in 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.

Examples:

Input: V=4, edges=[[0,1],[1,2]]

Output: 2

Explanation: Vertices {0,1,2} forms the first component and vertex 3 forms the second component.

Input: V = 7, edges = [[0, 1], [1, 2], [2, 3], [4, 5]]

Output: 3

Explanation:

The edges [0, 1], [1, 2], [2, 3] form a connected component with vertices {0, 1, 2, 3}.

The edge [4, 5] forms another connected component with vertices {4, 5}.

Therefore, the graph has 3 connected components: {0, 1, 2, 3}, {4, 5}, and the isolated vertices {6} (vertices 6 and any other unconnected vertices).

Input: V = 5, edges = [[0, 1], [1, 2], [3, 4]]

Constraints

  • 1 ≤ V, edges.length ≤ 104
  • 0 <= edges[i][0], edges[i][1] <= V-1
  • All edges are unique

Hints

  • Maintain a boolean array visited[V], where visited[i] = True means the node has already been counted in a component. Start DFS/BFS from an unvisited node, marking all reachable nodes in that component as visited.
  • Another approach is Union-Find (Disjoint Set Union) to keep track of components. Initially, each node is its own component. For each edge (a, b), merge the sets containing a and b. The number of unique parents in the DSU structure gives the number of components.

Company Tags

Micron Technology Chewy Teladoc Health JPMorgan Chase OYO Rooms NVIDIA Cerner Visa Roche Siemens Healthineers Reddit Goldman Sachs Mastercard Salesforce Red Hat Stripe AMD Databricks Johnson & Johnson Zynga PayPal Activision Blizzard Walmart Optum Epic Systems Google Microsoft Amazon Meta Apple Netflix Adobe