← All problems

Number of Connected Components

Medium graphsunion-finddfs LeetCode ↗
Given n nodes labeled 0..n-1 and a list of undirected edges, count the number of connected components in the graph. Consider both DFS and union-find solutions.

Hints (0/3 revealed)

Log in to reveal hints progressively.

Complexity

Time O(n α(n)), Space O(n)

Common pitfalls

  • Forgetting isolated nodes
  • Not path-compressing (still correct, slower)

Your solution

Log in to save your code and track progress.