1. Exactly n-1 edges
A tree on n nodes has precisely n-1 edges.
if (edges.length !== n - 1) {
return false;
}Typorithm · medium
Step 1 of 8 · intro card
Union-Find
A graph is a tree iff it has exactly n-1 edges and every union succeeds — together these force connected and acyclic.
A valid tree is connected and has no cycle.
First check there are exactly n-1 edges; fewer or more cannot be a tree.
Then union every edge: if any union fails, a cycle exists; with n-1 edges and no cycle, the graph must be fully connected.
A tree has exactly n-1 edges.
Any failed union = a cycle.
n-1 edges + no cycle = connected.
function validTree(n, edges) {
if (edges.length !== n - 1) {
return false;
}
const uf = new UnionFind(n);
for (const [a, b] of edges) {
if (!uf.union(a, b)) {
return false;
}
}
return true;
}Connect each part of the code to the concept before you type.
A tree on n nodes has precisely n-1 edges.
if (edges.length !== n - 1) {
return false;
}A failed union means the edge closes a cycle.
if (!uf.union(a, b)) {
return false;
}n-1 edges with no cycle force a single connected tree.
return trueRead 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.