Skip to content
Decoder

Connected Components in a Graph

Medium

Problem

You have n nodes labelled 0 to n - 1 and a list of undirected edges, where [a, b] joins a and b. Return the number of connected components: groups of nodes where every node can reach every other through edges.

Example 1

Input
n = 5, edges = [[0, 1], [1, 2], [3, 4]]
Output
2
Why
{0,1,2} and {3,4}

Example 2

Input
n = 3, edges = []
Output
3
Why
every node is alone

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.