28 · Union-Find & Minimum Spanning Trees

#323 Number of Connected Components in an Undirected Graph

frequently reported atLinkedInAmazonGoogle

the problem

In plain words

A graph has n nodes, numbered 0 to n − 1, and a list of undirected edges edges[i] = [a, b]. Two nodes belong to the same component if you can walk from one to the other along edges. Return how many components the graph has. (A node with no edges is a component on its own.)

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

out 2

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

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

out 1

One chain through all five nodes.

  • 1 ≤ n ≤ 2000
  • 1 ≤ edges.length ≤ 5000
  • edges[i] = [a, b] with 0 ≤ a, b < n and a ≠ b
  • No repeated edges

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code right here. Stuck for 20 minutes? Open one hint at a time.

This one is LeetCode Premium. You don't need a subscription: solve it right here. The free alternative linked above is the closest free practice; its label says how close it is.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #547
      Number of Provinces
      Mediumin Union-Find & MST
    2. #200
      Number of Islands
      Mediumin Graphs
    3. #1319