AlgoTales · Roadmap

Connected components

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Connected components are the separate "islands" in a network: groups where everyone can reach everyone else, but nobody can reach another group. Counting and labelling these islands tells you how your data splits into independent pieces.

Practical use cases

  • Web app: Finding friend circles. A community site wants to know how many separate groups of users exist, where no one in a group follows anyone outside. Starting a search from each unvisited user and labelling everyone reached gives the groups. A report then says "3 big communities and 40 isolated users" for the marketing team.
  • Web app: Duplicate customer accounts. A CRM has records linked when they share an email or a phone number. Records in one connected group are very likely the same person. Grouping them lets support merge 1,200 messy rows into about 800 real customers.
  • Web app: Seat map and image blobs. A booking page highlights blocks of adjacent free seats, and an upload tool counts separate spots in a scanned image. Both treat touching cells as links and count the groups, e.g. "one block of 6 seats together".
  • System: Network health checks. A monitoring tool checks whether all servers can still talk to each other. If the count of groups is more than one after a cable failure, part of the network is cut off and an alert goes out. A single number going from 1 to 2 is the simplest possible alarm, and it needs one quick pass over the machines to calculate.

The story: Counting the Friend Groups

The new school had 400 students, and the principal wanted to know how many separate friend groups existed. "If a student has no friend in common with another group, they are in a different group," she explained. Counting 400 faces by eye was hopeless.

Mira had a method. She went down the attendance list. If a student had not yet been put into a group, she started a new group: she told that student's friends, who told their friends, until every person reachable was marked "Group 7" or "Group 8". She never needed to ask the marked ones again.

When she reached the end of the list, the highest group number was the answer. Each time she had to start a fresh walk, she had discovered one more separate group.

Such a group, where everyone can reach everyone else, is a connected component. Counting them is one loop plus one DFS or BFS.

How to spot this problem, and where you need it

You have many items with links between them and you need to know how many separate groups there are, or whether two items belong to the same group.

Signs you need it

  • The wording says "number of groups", "islands", "clusters", "are these two connected?" or "how many separate networks".
  • Data comes as pairs that mean "A is related to B" and you want to merge related items into sets.
  • One search from a single start never covers everything, so you must restart from items not yet visited.

Where to use it in a project

  • Merging duplicate users, products or contacts that share an email, phone or address.
  • Community reports in a social site, or an admin check that every office in the network is reachable.

The solution

Keep a seen marker for every node and a counter. Loop over all nodes; whenever you meet one not yet seen, add one to the counter and run a BFS or DFS from it, marking everything it reaches. Everything marked in that run belongs to the same group, so you can also give them one group number. At the end, the counter is the number of components.

Payoff: Before: manually eyeballing 1,200 contact rows for duplicates. After: one pass groups them into about 800 people, and each group is labelled.

Explain it like I am 8

Spill buttons on a table and connect some with strings. Pick up one button and everything tied to it comes along. Put that bunch aside. Pick the next button still on the table and repeat. The number of bunches you picked up is the number of components.

How it works, step by step

  1. Keep a "seen" mark for every vertex, all empty at first.
  2. Loop over all vertices. If the vertex is not seen, you have found a new component: add 1 to your counter.
  3. Walk from it with DFS or BFS and mark everything reachable as seen (give them the same group number).
  4. Carry on with the loop. Seen vertices are skipped.
  5. The counter is the number of components, and the group numbers tell you who belongs together.

The code in four languages

PHP

<?php
// Returns a list of groups (each group is a list of vertices).
function components(array $graph): array {
    $seen = [];
    $groups = [];
    foreach (array_keys($graph) as $start) {
        if (isset($seen[$start])) continue;      // already in some group
        $group = [];
        $stack = [$start];
        $seen[$start] = true;
        while ($stack) {                         // walk everything reachable
            $node = array_pop($stack);
            $group[] = $node;
            foreach ($graph[$node] as $next) {
                if (!isset($seen[$next])) {
                    $seen[$next] = true;
                    $stack[] = $next;
                }
            }
        }
        sort($group);
        $groups[] = $group;                      // one fresh walk = one component
    }
    return $groups;
}

$graph = ['A'=>['B'], 'B'=>['A','C'], 'C'=>['B'], 'D'=>['E'], 'E'=>['D'],
          'F'=>['G'], 'G'=>['F','H'], 'H'=>['G']];
$groups = components($graph);
echo 'Components: ' . count($groups) . "\n";
foreach ($groups as $g) echo implode(',', $g) . "\n";

JavaScript

// Returns a list of groups (each group is a list of vertices).
function components(graph) {
  const seen = new Set();
  const groups = [];
  for (const start of Object.keys(graph)) {
    if (seen.has(start)) continue;               // already in some group
    const group = [];
    const stack = [start];
    seen.add(start);
    while (stack.length) {                       // walk everything reachable
      const node = stack.pop();
      group.push(node);
      for (const next of graph[node]) {
        if (!seen.has(next)) {
          seen.add(next);
          stack.push(next);
        }
      }
    }
    groups.push(group.sort());                   // one fresh walk = one component
  }
  return groups;
}

const graph = { A: ['B'], B: ['A','C'], C: ['B'], D: ['E'], E: ['D'],
                F: ['G'], G: ['F','H'], H: ['G'] };
const groups = components(graph);
console.log('Components: ' + groups.length);
groups.forEach(g => console.log(g.join(',')));

Java

import java.util.*;

public class Main {
    // Returns a list of groups (each group is a list of vertices).
    static List<List<String>> components(Map<String, List<String>> graph) {
        Set<String> seen = new HashSet<>();
        List<List<String>> groups = new ArrayList<>();
        for (String start : graph.keySet()) {
            if (seen.contains(start)) continue;          // already in some group
            List<String> group = new ArrayList<>();
            Deque<String> stack = new ArrayDeque<>();
            stack.push(start);
            seen.add(start);
            while (!stack.isEmpty()) {                   // walk everything reachable
                String node = stack.pop();
                group.add(node);
                for (String next : graph.get(node)) {
                    if (!seen.contains(next)) {
                        seen.add(next);
                        stack.push(next);
                    }
                }
            }
            Collections.sort(group);
            groups.add(group);                           // one fresh walk = one component
        }
        return groups;
    }

    public static void main(String[] args) {
        Map<String, List<String>> graph = new TreeMap<>(Map.of(
            "A", List.of("B"), "B", List.of("A", "C"), "C", List.of("B"),
            "D", List.of("E"), "E", List.of("D"),
            "F", List.of("G"), "G", List.of("F", "H"), "H", List.of("G")));
        var groups = components(graph);
        System.out.println("Components: " + groups.size());
        for (var g : groups) System.out.println(String.join(",", g));
    }
}

Go

package main

import (
	"fmt"
	"sort"
	"strings"
)

// components returns a list of groups (each group is a list of vertices).
func components(graph map[string][]string) [][]string {
	names := make([]string, 0, len(graph))
	for v := range graph {
		names = append(names, v)
	}
	sort.Strings(names) // fixed start order so the output is stable

	seen := map[string]bool{}
	var groups [][]string
	for _, start := range names {
		if seen[start] {
			continue // already in some group
		}
		var group []string
		stack := []string{start}
		seen[start] = true
		for len(stack) > 0 { // walk everything reachable
			node := stack[len(stack)-1]
			stack = stack[:len(stack)-1]
			group = append(group, node)
			for _, next := range graph[node] {
				if !seen[next] {
					seen[next] = true
					stack = append(stack, next)
				}
			}
		}
		sort.Strings(group)
		groups = append(groups, group) // one fresh walk = one component
	}
	return groups
}

func main() {
	graph := map[string][]string{
		"A": {"B"}, "B": {"A", "C"}, "C": {"B"}, "D": {"E"}, "E": {"D"},
		"F": {"G"}, "G": {"F", "H"}, "H": {"G"},
	}
	groups := components(graph)
	fmt.Println("Components:", len(groups))
	for _, g := range groups {
		fmt.Println(strings.Join(g, ","))
	}
}

Time: O(V + E) · Extra space: O(V). The outer loop visits each vertex once and every walk touches each edge of its own group once, so the total is still one sweep.

Watch out for

  • Resetting the "seen" marks inside the loop. They must persist across the whole loop or you count groups many times.
  • Starting the walk from only one vertex and calling it done. That finds one component, not all of them.
  • Forgetting isolated vertices. A vertex with no edges is a component of size 1.

Quick check

  1. When do you add 1 to the component counter?
    • When you start a walk from an unseen vertex
    • For every vertex
    • For every edge
  2. A graph has 5 vertices and no edges at all. How many components?
    • 1
    • 5
    • 0
  3. Total time to find all components of a graph with V vertices and E edges?
    • O(V × E)
    • O(V²) always
    • O(V + E)