Number of Connected Components in a Graph

MediumGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

An undirected graph has n nodes labeled 0 to n - 1. You are given edges, where edges[i] = [a, b] connects nodes a and b. Return the number of **connected components** in the graph. A connected component is a maximal set of nodes in which every pair is joined by some path. A node with no edges forms a component on its own. There are no self-loops or repeated edges. Target O(n + edges.length) time (up to inverse-Ackermann factors).

Examples

Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2
The components are {0, 1, 2} and {3, 4}.
Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1
A single path links all five nodes.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • 0 <= a, b < n and a != b
  • No edge appears twice

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems