intermediate · union-find · cycle detection · graphs

The first cable that closes a loop

Problem

Technicians lay cables between n machines (numbered 0 to n − 1) one at a time, in the order given. Report the first cable whose two machines were already connected by earlier cables — the first one that closes a loop — or report none if no cable does.

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

Constraints

  • 1 ≤ n ≤ 16
  • 0 ≤ cables ≤ 16
  • a cable from a machine to itself closes a loop at once

Examples

n = 4, cables = [[0, 1], [1, 2], [2, 0], [2, 3]] → [2, 0] — 0 and 2 are already connected through 1.

Show the solution

Union-find, stop at the first same-root cable

Union-find keeps the groups of connected machines as cables arrive. A cable inside a group is exactly a cable that closes a loop.

Why it is correct

Invariant: before cable i, two machines share a root exactly when cables 0…i − 1 connect them. If the ends of cable i share a root, there is already a path between them, and the cable completes a loop; no earlier cable did, or the loop would have stopped there. Otherwise the cable joins two groups and the union restores the invariant.

Complexity

Time O(n + m · α(n)), extra space O(n). At most one find pair and one union per cable, each amortized O(α(n)).

For contrast: For each cable, search the earlier cables (BFS or label propagation) for a path between its ends. That costs O(m · (n + m)) time and O(n + m) space.

Edge cases

  • A self-loop is reported immediately.
  • No loop at all: none.
  • A repeated cable closes a loop.

Common mistakes

  • Reporting the last cable that closes a loop instead of the first.
  • Comparing the machines themselves instead of their roots.

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 RedundantLink
{
    /// <summary>The first cable whose machines are already connected by earlier cables, or null. Union-find: O(n + m a(n)).</summary>
    public static (int A, int B)? Find(int n, IEnumerable<(int A, int B)> cables)
    {
        int[] parent = Enumerable.Range(0, n).ToArray();
        int[] size = Enumerable.Repeat(1, n).ToArray();
        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) return (a, b);
            if (size[ra] < size[rb]) (ra, rb) = (rb, ra);
            parent[rb] = ra;
            size[ra] += size[rb];
        }
        return null;
    }
}

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

from collections.abc import Iterable
 
 
def find_link(n: int, cables: Iterable[tuple[int, int]]) -> tuple[int, int] | None:
    """The first cable whose machines are already connected by earlier cables, or None. Union-find."""
    parent = list(range(n))
    size = [1] * 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:
            return (a, b)
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra
        size[ra] += size[rb]
    return None

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

package dev.bekadan.dsa.problems;
 
public final class RedundantLink {
    private RedundantLink() {
    }
 
    private static int find(int[] parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]]; // path halving
            x = parent[x];
        }
        return x;
    }
 
    /** The first cable {a, b} whose machines are already connected by earlier cables, or null. Union-find. */
    public static int[] find(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;
        }
        for (int[] cable : cables) {
            int ra = find(parent, cable[0]);
            int rb = find(parent, cable[1]);
            if (ra == rb) {
                return cable.clone();
            }
            if (size[ra] < size[rb]) {
                int t = ra;
                ra = rb;
                rb = t;
            }
            parent[rb] = ra;
            size[ra] += size[rb];
        }
        return null;
    }
}

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

#pragma once
 
#include <cstddef>
#include <numeric>
#include <optional>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::problems {
 
namespace redundant_link_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 redundant_link_detail
 
// The first cable whose machines are already connected by earlier cables, or nullopt. Union-find.
inline std::optional<std::pair<int, int>> redundant_link(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});
    for (const auto& [a, b] : cables) {
        auto ra = redundant_link_detail::find(parent, static_cast<std::size_t>(a));
        auto rb = redundant_link_detail::find(parent, static_cast<std::size_t>(b));
        if (ra == rb) return std::pair{a, b};
        if (size[ra] < size[rb]) std::swap(ra, rb);
        parent[rb] = ra;
        size[ra] += size[rb];
    }
    return std::nullopt;
}
 
}  // namespace bekadan::dsa::problems

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