Graph Count Connected ComponentsLoading saved progress…

Graph Count Connected Components

You're handed a social network of n people and a list of friendships. Some people form a tight clique where everyone is reachable through a chain of mutual friends; others sit in their own little group, or alone. A connected component is one such island — a maximal set of nodes where you can walk from any node to any other by following edges. Your job is to count how many islands the graph splits into.

Implement graphCountConnectedComponents(n, edges). The graph is undirected: an edge [u, v] means u and v are mutually connected, with no direction. Nodes are labelled 0 through n - 1.

Signature

// n: number — the count of nodes, labelled 0, 1, ..., n - 1.
// edges: Array<[number, number]> — each pair [u, v] connects node u and node v
//        (undirected: [u, v] and [v, u] mean the same thing).
// returns: number — how many connected components the graph has.
function graphCountConnectedComponents(n: number, edges: number[][]): number;

Examples

// Five nodes. Edges link 0-1-2 into one island and 3-4 into another.
// Node layout:  0 - 1 - 2     3 - 4
graphCountConnectedComponents(5, [
  [0, 1],
  [1, 2],
  [3, 4],
]); // → 2
// No edges at all: every node stands alone, so each is its own component.
graphCountConnectedComponents(4, []); // → 4
// Two pairs and one node nobody is connected to.
// Node layout:  0 - 1     2 - 3     4
graphCountConnectedComponents(5, [
  [0, 1],
  [2, 3],
]); // → 3

Notes

  • Undirected edges. [u, v] connects both ways. When you build your graph, record u as a neighbour of v and v as a neighbour of u.
  • Nodes are 0..n-1. Every label in that range is a real node, even if no edge ever mentions it. n is the source of truth for how many nodes exist — not the edge list.
  • Isolated nodes count. A node with zero edges is a component of size one. With n = 3 and no edges, the answer is 3.
  • n = 0 returns 0. No nodes, no components.
  • No self-loops or duplicate edges. Assume the input never contains an edge like [2, 2] or the same pair twice. You don't need to defend against them — though, as it happens, the standard solutions handle both gracefully.
  • Don't worry about which nodes belong to which component, or the size of each component. You only return the count.
Loading editor…