I’m using union-find to detect the first edge that creates a cycle in an undirected graph, but this sometimes returns null even when a cycle exists. I suspect the issue is in how parents are updated during union. What is wrong here?
function hasCycle(edges, n) {
const p = Array.from({ length: n }, (_, i) => i);
const find = x => p[x] === x ? x : find(p[x]);
for (const [a, b] of edges) {
if (find(a) === find(b)) return [a, b];
p[a] = b;
}
return null;
}
Quelly