Cycle detection
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Cycle detection with union-find checks whether adding a link would connect two items that are already connected. If yes, the new link closes a loop. This is a fast way to reject or flag circular connections as you add them.
Practical use cases
- Web app: Preventing loops in a category tree. In a CMS, an editor tries to move category "Shoes" under "Sports Shoes", which is already inside "Shoes". The page should refuse it. Checking whether both are already in the same group tells you immediately that this move would create a loop.
- Web app: Wiring or workflow designer. A web-based flowchart or circuit tool lets users draw connectors. When a user connects two blocks that are already linked through other blocks, the tool highlights a loop warning at once, instead of re-searching the entire drawing. The user fixes the mistake at the moment it happens, instead of discovering a broken diagram later.
- System: Kruskal and road planning. Algorithms that build cheap networks, like Kruskal, skip any link that would form a loop, and road planners avoid redundant roads the same way. Each new road or wire is judged in a moment, so large plans stay practical to build up piece by piece.
The story: The Diwali Lamp Wiring That Went Round in Circles
Every Diwali, Raju's lane strung lights between lamp posts. Pappu uncle was the wiring expert, with a strict rule: "The wires must make a tree, never a ring." A ring of wires wastes cable and, worse, is a short-circuit risk when it is wired wrongly.
This year there were dozens of posts and a long list of wires to lay. Mira peeked at the list and said, "How will you know in advance if a wire closes a ring?" Pappu uncle sighed. "I draw the lamp map after every wire." He had been up past midnight doing that.
Mira offered the Union-Find trick. Each lamp starts in its own group. For each planned wire, ask: are the two lamps already in the same group? If not, plug it in and merge the groups. If yes, they are already linked by another path, so this wire would complete a loop. Spot it, skip it, and raise a flag.
That is cycle detection in an undirected graph with Union-Find. One pass over the wires, one find-pair per wire, and the first wire that connects two lamps of the same group is the one that closes a cycle.
How to spot this problem, and where you need it
Links are added one at a time and you must reject or flag any link that would make a loop, without rechecking the whole structure every time.
Signs you need it
- The rule says "no circular dependency", "must stay a tree" or "detect a redundant connection".
- Users add connections one by one and need instant feedback.
- You currently run a full graph search after each new link to look for loops.
- The graph has no direction (a link works both ways).
Where to use it in a project
- Hierarchy editors such as categories, org charts and menus that must stay loop-free.
- Drawing, circuit and network design tools that warn about redundant links.
The solution
Keep a union-find over the items. For each new link, find the leaders of both ends. If they are the same, the two ends are already connected, so this link would form a cycle: reject or report it. If they differ, accept the link and union the two groups. Each check is almost instant.
Payoff: Before: searching the whole graph on every new link. After: two lookups and one comparison per link.
Explain it like I am 8
You and your friends hold hands in a chain. If two kids who are already in the chain try to hold hands again, the chain bends into a circle. Union-Find notices that right away.
How it works, step by step
- Start with every node in its own set.
- Read the edges one at a time: for each pair
(a, b), computefind(a)andfind(b). - Different roots? The edge is safe; union them and go on.
- Same root? They are already connected, so this edge closes a cycle. Report it.
- This is for undirected graphs. Directed graphs need a different method (a depth-first walk with colours).
The code in four languages
PHP
<?php
// Returns the first edge that closes a cycle, or null if the graph has none
function firstCycleEdge(int $n, array $edges): ?array {
$parent = range(0, $n - 1);
$find = function (int $x) use (&$parent): int {
while ($parent[$x] !== $x) {
$parent[$x] = $parent[$parent[$x]]; // path halving
$x = $parent[$x];
}
return $x;
};
foreach ($edges as [$a, $b]) {
$ra = $find($a);
$rb = $find($b);
if ($ra === $rb) return [$a, $b]; // already connected: this closes a loop
$parent[$ra] = $rb; // safe wire: merge the groups
}
return null;
}
$wires = [[0, 1], [1, 2], [3, 4], [2, 3], [4, 0]];
$bad = firstCycleEdge(6, $wires);
echo $bad ? "Cycle closed by wire " . $bad[0] . "-" . $bad[1] : "No cycle";
echo "\n";
$tree = firstCycleEdge(4, [[0, 1], [1, 2], [2, 3]]);
echo $tree ? "Cycle" : "No cycle";
echo "\n";JavaScript
// Returns the first edge that closes a cycle, or null if the graph has none
function firstCycleEdge(n, edges) {
const parent = Array.from({ length: n }, (_, i) => i);
const find = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]]; // path halving
x = parent[x];
}
return x;
};
for (const [a, b] of edges) {
const ra = find(a);
const rb = find(b);
if (ra === rb) return [a, b]; // already connected: this closes a loop
parent[ra] = rb; // safe wire: merge the groups
}
return null;
}
const wires = [[0, 1], [1, 2], [3, 4], [2, 3], [4, 0]];
const bad = firstCycleEdge(6, wires);
console.log(bad ? "Cycle closed by wire " + bad[0] + "-" + bad[1] : "No cycle");
const tree = firstCycleEdge(4, [[0, 1], [1, 2], [2, 3]]);
console.log(tree ? "Cycle" : "No cycle");Java
public class Main {
// Returns the first edge that closes a cycle, or null if the graph has none
static int[] firstCycleEdge(int n, int[][] edges) {
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
for (int[] e : edges) {
int ra = find(parent, e[0]);
int rb = find(parent, e[1]);
if (ra == rb) return e; // already connected: this closes a loop
parent[ra] = rb; // safe wire: merge the groups
}
return null;
}
static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // path halving
x = parent[x];
}
return x;
}
public static void main(String[] args) {
int[][] wires = {{0, 1}, {1, 2}, {3, 4}, {2, 3}, {4, 0}};
int[] bad = firstCycleEdge(6, wires);
System.out.println(bad != null ? "Cycle closed by wire " + bad[0] + "-" + bad[1] : "No cycle");
int[] tree = firstCycleEdge(4, new int[][]{{0, 1}, {1, 2}, {2, 3}});
System.out.println(tree != null ? "Cycle" : "No cycle");
}
}Go
package main
import "fmt"
// firstCycleEdge returns the first edge that closes a cycle,
// or ok == false if the graph has none.
func firstCycleEdge(n int, edges [][2]int) (edge [2]int, ok bool) {
parent := make([]int, n)
for i := range parent {
parent[i] = i
}
find := func(x int) int {
for parent[x] != x {
parent[x] = parent[parent[x]] // path halving
x = parent[x]
}
return x
}
for _, e := range edges {
ra, rb := find(e[0]), find(e[1])
if ra == rb { // already connected: this closes a loop
return e, true
}
parent[ra] = rb // safe wire: merge the groups
}
return [2]int{}, false
}
func main() {
wires := [][2]int{{0, 1}, {1, 2}, {3, 4}, {2, 3}, {4, 0}}
if bad, ok := firstCycleEdge(6, wires); ok {
fmt.Printf("Cycle closed by wire %d-%d\n", bad[0], bad[1])
} else {
fmt.Println("No cycle")
}
if _, ok := firstCycleEdge(4, [][2]int{{0, 1}, {1, 2}, {2, 3}}); ok {
fmt.Println("Cycle")
} else {
fmt.Println("No cycle")
}
}Time: O(m), almost linear · Extra space: O(n). One find-pair per wire, and with path compression each find is nearly constant time.
Watch out for
- Using this on a directed graph. A directed edge that reaches an "already connected" node is not necessarily a cycle.
- Forgetting parallel edges: two wires between the same pair of lamps form a cycle of length two, and this method catches that too, since the second finds equal roots.
- Comparing
parent[a] === parent[b]rather than the roots, which misses cycles through deeper levels.
Quick check
- When does an undirected edge (a, b) close a cycle?
- When a < b
- When find(a) equals find(b)
- When a has no parent
- When b is a root
- What do you do with an edge whose roots differ?
- Delete one node
- Stop
- Report a cycle
- Union them and continue
- Which graphs does this simple method suit?
- Directed graphs only
- Undirected graphs
- Weighted graphs only
- Graphs without nodes