Number of Connected Components in an Undirected Graph
Social Network Analysis You're analyzing friend groups in a social network. Given n users (labeled 0 to n-1) and friendship connections as edges where edges[i] = [user_a, user_b], find how many distinct friend groups exist. A friend group is a set of users who are all connected either directly or through mutual friends. Example: n = 5, edges = [[0,1],[1,2],[3,4]] → 2 groups: {0,1,2} and {3,4}
Components are traversals you had to restart. I walk each unvisited node once, then count how many times I started over.
Examples
You write
count_components(n, edges)
Example 1
- Input
- n = 5, edges = [[0,1],[1,2],[3,4]]
- returns
- 2
Example 2
- Input
- n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
- returns
- 1
The pattern behind it
BFS & DFS
I reach for it when
- You walk a grid, a graph or a tree and visit each cell once.
- The word shortest appears and every step costs the same.
Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.
All 52 BFS & DFS problemsGraphs
I reach for it when
- The input is edges, prerequisites or connections.
- You need cycles, an ordering or connected groups.
Say this before you type. Say whether the edges are directed, and which of the three jobs you are doing.
All 32 Graphs problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.