1. 1-indexed nodes
Nodes are labeled 1..n, so size is edges.length + 1.
new UnionFind(edges.length + 1)Typorithm · medium
Step 1 of 8 · intro card
Union-Find
Union each edge; the first edge whose union fails connects two already-joined nodes and is the redundant one.
A tree of n nodes has n - 1 edges; one extra edge creates exactly one cycle.
Unioning edges one by one, the redundant edge is the first whose endpoints already share a root.
When union returns false, both nodes were already connected, so this edge closes the cycle.
Extra edge forms one cycle.
union returning false flags it.
Return the first failing edge.
function findRedundantConnection(edges) {
const uf = new UnionFind(edges.length + 1);
for (const [a, b] of edges) {
if (!uf.union(a, b)) {
return [a, b];
}
}
return [];
}Connect each part of the code to the concept before you type.
Nodes are labeled 1..n, so size is edges.length + 1.
new UnionFind(edges.length + 1)A union that returns false means both endpoints already connect.
if (!uf.union(a, b)) {That edge is the one closing a cycle.
return [a, b]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.