Graph Valid Tree
MediumNeetCode 150 GraphsZenefitsProblem
There are n nodes, numbered 0 to n - 1, and a list edges where each pair
[a, b] is an undirected edge between nodes a and b.
Return true if these edges make the nodes a tree: every node can be reached from every other one,
and there is no circle. Otherwise return false.
Constraints
- 1 ≤ n ≤ 2000
- 0 ≤ edges.length ≤ 5000
- 0 ≤ a, b < n, a ≠ b, and no edge is repeated ([a, b] and [b, a] count as the same edge)
Examples: pick one to animate
Solutions
Time: After the edge count check there are n − 1 edges, and each makes two finds and one merge. With union by size and path halving each costs almost constant time (the inverse Ackermann function α).
Space: The parent and size arrays hold one number per node.
A tree on n nodes has exactly n − 1 edges, so any other count is an immediate false. Then give every node its own set and add the edges one by one. An edge whose two ends already share a root would close a circle, so the answer is false. If all n − 1 edges join different sets there is no circle, and n − 1 edges without a circle must connect all n nodes.