Skip to main content
46

Number of Connected Components in an Undirected Graph

Mediumgraphsunion find

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:GraphsRead the beginner guide

You're given n nodes labeled 0 to n - 1, and a list of undirected edges, where [a, b] connects a and b. Return the number of connected components.

Understand the problem

  • Undirected edges work both ways: [0, 1] connects 0 to 1 and 1 to 0.
  • A connected component is a group of nodes where you can get from any node to any other by following edges, and nothing outside the group is connected to it. Think of separate "islands" of nodes.
  • A node with no edges is a component on its own.

Example 1

text
Input:  n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output: 2

  0 ─ 1 ─ 2     3 ─ 4

{0, 1, 2} and {3, 4}.

Example 2

text
Input:  n = 5, edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
Output: 1

One long chain: everything is connected.

Example 3

text
Input:  n = 3, edges = []
Output: 3

No edges, so each node is its own component.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • No repeated edges or self-loops.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Start with every node in its own group, and for each edge merge the two groups if they're different; the number of groups left is the answer.

    Approach 1: DFS from every unvisited node (the Python solution)

    This is Number of Islands, on a graph given as a list of edges instead of a grid:

    1. Build an adjacency list: for each node, the list of its neighbors (add each edge in both directions).
    2. Loop over the nodes. When you find one that isn't visited yet, it's a new component: add 1, then visit everything reachable from it with a stack, marking each node visited.

    Approach 2: Union-Find (the JavaScript/TypeScript solution)

    Union-Find (also called Disjoint Set Union) is a small structure that keeps track of groups and can merge them quickly.

    • Each group has one representative (a "leader" node).
    • A parent array: each node points to another node in its group, and following the pointers always leads to the representative, which points to itself.
    • find(x): follow parent from x until you reach a node that points to itself. That's x's representative.
    • union: find both representatives; if they differ, point one at the other. The two groups are now one.

    Start with every node as its own group (parent[i] = i), so the count is n. For each edge [a, b]:

    • if find(a) !== find(b), they were in different groups: merge them, and the count drops by 1;
    • otherwise they're already connected, and nothing changes.

    Path compression: while find walks up, it also points each node it passes closer to the representative (parent[x] = parent[parent[x]]). Later finds on the same nodes are then almost instant.

    Step by step (Union-Find)

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

    Edgefind(a)find(b)Different?ActionGroupsCount
    start{0} {1} {2} {3} {4}5
    [0, 1]01yesparent[0] = 1{0,1} {2} {3} {4}4
    [1, 2]12yesparent[1] = 2{0,1,2} {3} {4}3
    [3, 4]34yesparent[3] = 4{0,1,2} {3,4}2

    Answer: 2.

    The code

    The reference solution is below, with comments on every important line. JavaScript and TypeScript use Union-Find; Python uses DFS, so you can see both.

    How fast is it?

    With V nodes and E edges:

    • DFS: O(V + E) time and memory.
    • Union-Find: about O(V + E) time (each find is nearly constant thanks to path compression) and O(V) memory.

    Common mistakes

    • Adding each edge in only one direction for DFS. Undirected edges must go in both neighbor lists.
    • Forgetting nodes with no edges. They still count as components. (Both approaches handle this naturally, as long as you loop over all n nodes or start the count at n.)
    • Merging nodes instead of representatives in Union-Find: parent[a] = b is wrong when a isn't its group's representative. Always merge find(a) with find(b).

    Going deeper

    • Union-Find shines when edges arrive one at a time and you need the answer after each one, or need to answer "are a and b connected?" quickly.
    • An edge whose two ends are already in the same group closes a cycle. That's exactly how Graph Valid Tree detects cycles.

    Reference solution

    js
    /**
     * @param {number} n
     * @param {number[][]} edges
     * @return {number}
     */
    export default function countComponents(n, edges) {
      // Union-Find: every node starts as its own group, pointing to itself.
      const parent = Array.from({ length: n }, (_, i) => i)
      // Follow parent pointers up to the group's representative (the node pointing to itself).
      function find(x) {
        while (parent[x] !== x) {
          parent[x] = parent[parent[x]] // path compression: skip a level for next time
          x = parent[x]
        }
        return x
      }
    
      let count = n // n separate groups to start
      for (const [a, b] of edges) {
        const rootA = find(a)
        const rootB = find(b)
        // Different groups: merge them, so there's one fewer component.
        // (Same group: they're already connected, nothing changes.)
        if (rootA !== rootB) {
          parent[rootA] = rootB
          count--
        }
      }
      return count
    }
    ts
    export default function countComponents(n: number, edges: number[][]): number {
      // Union-Find: every node starts as its own group, pointing to itself.
      const parent = Array.from({ length: n }, (_, i) => i)
      // Follow parent pointers up to the group's representative (the node pointing to itself).
      function find(x: number): number {
        while (parent[x] !== x) {
          parent[x] = parent[parent[x]] // path compression: skip a level for next time
          x = parent[x]
        }
        return x
      }
    
      let count = n // n separate groups to start
      for (const [a, b] of edges) {
        const rootA = find(a)
        const rootB = find(b)
        // Different groups: merge them, so there's one fewer component.
        // (Same group: they're already connected, nothing changes.)
        if (rootA !== rootB) {
          parent[rootA] = rootB
          count--
        }
      }
      return count
    }
    python
    def count_components(n: int, edges: list[list[int]]) -> int:
        # Adjacency list: each undirected edge goes into BOTH nodes' lists.
        neighbors = [[] for _ in range(n)]
        for a, b in edges:
            neighbors[a].append(b)
            neighbors[b].append(a)
    
        visited = [False] * n
        count = 0
        for start in range(n):
            if visited[start]:
                continue  # already part of a component we counted
            # An unvisited node starts a new component: count it, then visit all of it.
            count += 1
            visited[start] = True
            stack = [start]
            while stack:
                for nxt in neighbors[stack.pop()]:
                    if not visited[nxt]:
                        visited[nxt] = True  # mark when pushing, so it's never pushed twice
                        stack.append(nxt)
        return count