Skip to content
mlmentorship

Graph Valid Tree

Combine an exact edge count with full undirected reachability, then adapt the proof for forests or an explicit labeled vertex universe.

Published · 19 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Graph Valid Tree

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

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

Require the exact tree edge count and reach every declared vertexUse 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.Exact edge count plus completeundirected reachabilityFive declared nodes, four undirectededges. If connected, those edges areexactly a spanning tree, with noneleft to close a cycle.01234Mark on push. Stack top is at theright; seen means discovered, notfully expanded.Seed only: stack 0Discovered: 0Expanded 0: stack 1, 2Discovered: 0, 1, 2Expanded 2: stack 1Discovered: 0, 1, 2Expanded 1: stack 3, 4Discovered: 0, 1, 2, 3, 4Expanded 4: stack 3Discovered: 0, 1, 2, 3, 4Expanded 3: stack emptyDiscovered: 0, 1, 2, 3, 4All five discovered: accept. Adiscovered neighbor alone is not acycle test; the reverse entry of eachundirected edge is expected.Count-only failure: triangle plusisolated node three0123Four nodes, three edges, but onlythree reachable. A triangle withoutthe isolate is connected, yet failsthe edge-count gate. Both conditionsmatter.Changed target: edges zero-one andtwo-three form a forest, not onetree. Forest validation dropsconnectivity but rejectswithin-component edges, loops andrepeated edges.Keep the full declared labeluniverse, including isolates. Onenode without edges is a tree; zeronodes is not. Arbitrary labels needan explicit map, not labels inferredonly from edges.DFS inputs passing the count gateneed linear graph work and storage.Directed rooted trees requiredifferent incoming-edge and directionconditions.
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?
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 expandingstack, top at rightseen
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 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 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.
01234
seennot seeded
Original undirected adjacency lists
012
1034
20
31
41
stack: top at rightempty
edgeTopology0-1, 0-2, 1-3, 1-4rowMeaningrow index = node; cells = adjacent nodesadjacency0:[1,2]; 1:[0,3,4]; 2:[0]; 3:[1]; 4:[1]edgeCheck4 = n-1
queue
[]
edge topology
0-1, 0-2, 1-3, 1-4
row meaning
row index = node; cells = adjacent nodes

Recognize it
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

Require the exact tree edge count and reach every declared vertexUse 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.Exact edge count plus completeundirected reachabilityFive declared nodes, four undirectededges. If connected, those edges areexactly a spanning tree, with noneleft to close a cycle.01234Mark on push. Stack top is at theright; seen means discovered, notfully expanded.Seed only: stack 0Discovered: 0Expanded 0: stack 1, 2Discovered: 0, 1, 2Expanded 2: stack 1Discovered: 0, 1, 2Expanded 1: stack 3, 4Discovered: 0, 1, 2, 3, 4Expanded 4: stack 3Discovered: 0, 1, 2, 3, 4Expanded 3: stack emptyDiscovered: 0, 1, 2, 3, 4All five discovered: accept. Adiscovered neighbor alone is not acycle test; the reverse entry of eachundirected edge is expected.Count-only failure: triangle plusisolated node three0123Four nodes, three edges, but onlythree reachable. A triangle withoutthe isolate is connected, yet failsthe edge-count gate. Both conditionsmatter.Changed target: edges zero-one andtwo-three form a forest, not onetree. Forest validation dropsconnectivity but rejectswithin-component edges, loops andrepeated edges.Keep the full declared labeluniverse, including isolates. Onenode without edges is a tree; zeronodes is not. Arbitrary labels needan explicit map, not labels inferredonly from edges.DFS inputs passing the count gateneed linear graph work and storage.Directed rooted trees requiredifferent incoming-edge and directionconditions.
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.
01234
seennot seeded
Original undirected adjacency lists
012
1034
20
31
41
stack: top at rightempty
edgeTopology0-1, 0-2, 1-3, 1-4rowMeaningrow index = node; cells = adjacent nodesadjacency0:[1,2]; 1:[0,3,4]; 2:[0]; 3:[1]; 4:[1]edgeCheck4 = n-1
queue
[]
edge topology
0-1, 0-2, 1-3, 1-4
row meaning
row index = node; cells = adjacent nodes

Recognize it
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 . Any graph entering DFS has , so adjacency, discovery state and traversal use space and 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.

  1. 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 amortized; storage is .

  2. 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 .

Rebuild the Proof

Which condition distinguishes one tree from a forest?

Answer: One connected component. An acyclic forest with components has edges. Requiring gives .