intermediate · union-find · disjoint sets · connected components · graphs

How many separate networks?

Problem

A data centre has n machines numbered 0 to n − 1 and a list of cables, each joining two machines (both directions). Machines that can reach each other through cables form one network. How many networks are there?

In the lab, enter the cables as one list: a b a b …

Constraints

  • 1 ≤ n ≤ 16
  • 0 ≤ cables ≤ 16
  • a cable may join a machine to itself or repeat an earlier cable

Examples

n = 5, cables = [[0, 1], [1, 2], [3, 4]] → 2

Show the solution

Union-find with union by size and path halving

Each network is a tree whose root names it. Joining two networks means hanging one root under the other; the count goes down only when the roots differ.

Why it is correct

Invariant: two machines have the same root exactly when the cables processed so far connect them, and networks equals the number of roots. A cable between machines with the same root adds no connection, so nothing changes. A cable between different roots connects exactly those two networks; making one root the child of the other merges them and reduces the count by one.

Complexity

Time O(n + m · α(n)), extra space O(n). With union by size and path halving each find costs amortized O(α(n)), the inverse Ackermann function, which is at most 4 for any realistic n.

For contrast: Label each machine with its own number; repeatedly set both ends of every cable to the smaller label until stable; count labels. That costs O(n · m) time and O(n) space.

Edge cases

  • No cables: n networks.
  • A cable from a machine to itself changes nothing.
  • Repeated cables change nothing.

Common mistakes

  • Comparing a and b instead of find(a) and find(b).
  • Setting parent[a] = b instead of linking the roots, which can split a tree.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class CountNetworks
{
    /// <summary>Connected components of n machines joined by cables. Union-find (union by size, path halving): O(n + m a(n)).</summary>
    public static int Count(int n, IEnumerable<(int A, int B)> cables)
    {
        int[] parent = Enumerable.Range(0, n).ToArray();
        int[] size = Enumerable.Repeat(1, n).ToArray();
        int networks = n;
        int Find(int x)
        {
            while (parent[x] != x)
            {
                parent[x] = parent[parent[x]]; // path halving
                x = parent[x];
            }
            return x;
        }
        foreach (var (a, b) in cables)
        {
            int ra = Find(a), rb = Find(b);
            if (ra == rb) continue;
            if (size[ra] < size[rb]) (ra, rb) = (rb, ra);
            parent[rb] = ra; // the smaller tree goes under the larger root
            size[ra] += size[rb];
            networks--;
        }
        return networks;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/CountNetworks.cs

from collections.abc import Iterable
 
 
def count(n: int, cables: Iterable[tuple[int, int]]) -> int:
    """Connected components of n machines joined by cables. Union-find (union by size, path halving)."""
    parent = list(range(n))
    size = [1] * n
    networks = n
 
    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]  # path halving
            x = parent[x]
        return x
 
    for a, b in cables:
        ra, rb = find(a), find(b)
        if ra == rb:
            continue
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra  # the smaller tree goes under the larger root
        size[ra] += size[rb]
        networks -= 1
    return networks

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/count_networks.py

package dev.bekadan.dsa.problems;
 
public final class CountNetworks {
    private CountNetworks() {
    }
 
    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]]; // path halving
            x = parent[x];
        }
        return x;
    }
 
    /** Connected components of n machines joined by cables {a, b}. Union-find (union by size, path halving). */
    public static int count(int n, int[][] cables) {
        int[] parent = new int[n];
        int[] size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        int networks = n;
        for (int[] cable : cables) {
            int ra = find(parent, cable[0]);
            int rb = find(parent, cable[1]);
            if (ra == rb) {
                continue;
            }
            if (size[ra] < size[rb]) {
                int t = ra;
                ra = rb;
                rb = t;
            }
            parent[rb] = ra; // the smaller tree goes under the larger root
            size[ra] += size[rb];
            networks--;
        }
        return networks;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/CountNetworks.java

#pragma once
 
#include <cstddef>
#include <numeric>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::problems {
 
namespace count_networks_detail {
inline std::size_t find(std::vector<std::size_t>& parent, std::size_t x) {
    while (parent[x] != x) {
        parent[x] = parent[parent[x]];  // path halving
        x = parent[x];
    }
    return x;
}
}  // namespace count_networks_detail
 
// Connected components of n machines joined by cables. Union-find (union by size, path halving).
inline int count_networks(std::size_t n, const std::vector<std::pair<int, int>>& cables) {
    std::vector<std::size_t> parent(n), size(n, 1);
    std::iota(parent.begin(), parent.end(), std::size_t{0});
    int networks = static_cast<int>(n);
    for (const auto& [a, b] : cables) {
        auto ra = count_networks_detail::find(parent, static_cast<std::size_t>(a));
        auto rb = count_networks_detail::find(parent, static_cast<std::size_t>(b));
        if (ra == rb) continue;
        if (size[ra] < size[rb]) std::swap(ra, rb);
        parent[rb] = ra;  // the smaller tree goes under the larger root
        size[ra] += size[rb];
        --networks;
    }
    return networks;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/count_networks.hpp