With exactly n-1 undirected edges, reaching all n nodes proves the graph is one connected acyclic tree.
Problem trace
Require the exact tree edge count and reach every declared vertex
Read it this way:Use both edge count and reachability. The five-node example has four edges and DFS discovers every node. Mark on push; discovered is not fully expanded. Seeing the reverse of an undirected edge is not cycle evidence by itself. A triangle plus an isolate passes the count but fails connectivity. Forests relax connectivity, not acyclicity. Keep isolated vertices in the explicit universe; directed trees need a different proof. Does a previously discovered neighbor alone prove an undirected cycle?
Sources and provenance
Full interview answer 19 min read
Determine whether all supplied vertices and undirected edges form one connected tree without cycles.
Problem
Input. A nonnegative node_count and a list edges of undirected endpoint pairs from 0 through node_count - 1.
Output. Return True exactly when the graph is connected and contains no cycle.
Rules. Include isolated vertices in the declared vertex set.
Self-loops and repeated edges count as edges; neither can belong to a valid tree.
Leave the inputs unchanged. Zero nodes is not a tree; one node with no edges is a tree.
Example. Five nodes with edges [[0, 1], [0, 2], [0, 3], [1, 4]] return True.
Three nodes with [[0, 1]] return False because node 2 is disconnected.
Picture
For five nodes, [[0,1],[0,2],[1,3],[1,4]] passes the four-edge gate. DFS then reaches every node.
After expanding
stack, top at right
seen
Seed only
[0]
{0}
0
[1,2]
{0,1,2}
2
[1]
{0,1,2}
1
[3,4]
{0,1,2,3,4}
4, then 3
[]
{0,1,2,3,4}
seen means discovered, not fully expanded. Mark on push so a vertex enters the stack once.
A seen neighbor does not itself prove a cycle. Every undirected edge appears in both adjacency lists.
Both tests matter. A triangle plus isolated node three has V−1=3 edges but fails reachability:
0---1 3 \ / 2
Connectivity alone also allows that triangle. Together the conditions suffice: a connected graph contains a spanning tree with V−1 edges.
If those are all its edges, none remains to close a cycle.
This proof is for undirected graphs. Directed rooted trees need different direction and incoming-edge conditions.
Problem trace
Require the exact tree edge count and reach every declared vertex
Input and goalCheck whether undirected edges form one valid tree.
Pass the edge-count gateFive nodes and four edges pass the count gate. Build the undirected adjacency lists.
Use this proof when an undirected graph must be exactly one tree: reject any edge count other than n-1, then test whether one traversal reaches every vertex.
Keep true
seen contains every discovered vertex and stack contains discovered vertices not yet expanded. After the n-1 gate passes, full reachability is equivalent to being a tree.
Reuse it
Combine a cheap global structural count with one local traversal invariant. Similar count-plus-connectivity proofs validate arborescences, spanning trees, and network skeletons.
Five nodes and four edges pass the count gate. Build the undirected adjacency lists. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can a five-node graph with four edges still fail to be a tree?
Reference drawing
Problem trace
Require the exact tree edge count and reach every declared vertex
Execution trace
Input and goalCheck whether undirected edges form one valid tree.
Pass the edge-count gateFive nodes and four edges pass the count gate. Build the undirected adjacency lists.
Use this proof when an undirected graph must be exactly one tree: reject any edge count other than n-1, then test whether one traversal reaches every vertex.
Keep true
seen contains every discovered vertex and stack contains discovered vertices not yet expanded. After the n-1 gate passes, full reachability is equivalent to being a tree.
Reuse it
Combine a cheap global structural count with one local traversal invariant. Similar count-plus-connectivity proofs validate arborescences, spanning trees, and network skeletons.
Five nodes and four edges pass the count gate. Build the undirected adjacency lists. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can a five-node graph with four edges still fail to be a tree?
Read it this way:Use both edge count and reachability. The five-node example has four edges and DFS discovers every node. Mark on push; discovered is not fully expanded. Seeing the reverse of an undirected edge is not cycle evidence by itself. A triangle plus an isolate passes the count but fails connectivity. Forests relax connectivity, not acyclicity. Keep isolated vertices in the explicit universe; directed trees need a different proof. Does a previously discovered neighbor alone prove an undirected cycle?
Code
def valid_tree(node_count: int, edges: list[list[int]]) -> bool: if len(edges) != node_count - 1: return False graph = [[] for _ in range(node_count)] for first, second in edges: graph[first].append(second) graph[second].append(first) seen = {0} stack = [0] while stack: for neighbor in graph[stack.pop()]: if neighbor not in seen: seen.add(neighbor) stack.append(neighbor) return len(seen) == node_count
The edge-count gate costs O(1). Any graph entering DFS has E=V−1, so adjacency, discovery state and traversal use O(V) space and O(V+E)=O(V) work.
Change Connectivity or the Label Universe
Start from valid_tree. Changing either the accepted structure or its vertex names changes what must be checked.
Allow a disconnected forest.
New task: Accept any acyclic undirected graph, including isolated vertices.
Picture and change: Keep a representative for each component. An edge within one component closes a cycle; an edge between components joins them.
Remove the single-tree edge-count gate. Use size balancing and path halving:
Code: Complete replacement:
def valid_forest(node_count, edges): parent = list(range(node_count)) size = [1] * node_count def find(node): while node != parent[node]: parent[node] = parent[parent[node]] node = parent[node] return node for first, second in edges: first, second = find(first), find(second) if first == second: return False if size[first] < size[second]: first, second = second, first parent[second] = first size[first] += size[second] return True
Check: Four vertices with [[0,1],[2,3]] form a forest, not one tree. A triangle fails. A self-loop or second copy of an undirected edge also fails.
Use when: Connectivity is unnecessary. Zero vertices with no edges now passes. Work is O(V+Eα(V+1)) amortized; storage is O(V).
Retain arbitrary labels and isolated vertices.
New task: Input labels are strings or sparse IDs.
Picture and change: Map an explicit complete vertex list to dense indices. Do not infer that list from edges, which omit isolates.
Code: Uses valid_tree above:
def labeled_tree(vertices, edges): positions = {value: index for index, value in enumerate(vertices)} if len(positions) != len(vertices): return False dense = [[positions[first], positions[second]] for first, second in edges] return valid_tree(len(vertices), dense)
Check: Vertices ["a","b","c"] with edges [["a","b"],["b","c"]] pass. Removing the second edge leaves "c" isolated and fails.
Use when: Labels do not define a dense universe. Labels must be hashable. Repeated listed vertices fail; unlisted endpoints raise KeyError.
Expected mapping work and total storage are O(V+E).
Rebuild the Proof
Which condition distinguishes one tree from a forest?
Answer: One connected component. An acyclic forest with C components has V−C edges. Requiring C=1 gives V−1.