Graph Valid Tree solution explained

An undirected graph with n nodes is a valid tree when it has exactly n - 1 edges and every node can reach every other node. Check the edge count first, then confirm connectivity with one breadth-first search or with union-find, which also catches the first edge that closes a loop. Either solution runs in about O(V + E) time.

By Published 9 min read

The problem, in plain terms

You get a number n and a list of connections between nodes labeled 0 to n - 1. Each connection is a two-way link. Return true if these links form one tree: a single connected network with no loops, so there is exactly one route between any two nodes. Return false otherwise.

Graph A: n = 5, edges = [0-1, 1-2, 1-3, 3-4]     -> true
         4 edges, everything reachable from 0

Graph B: n = 5, edges = [0-1, 1-2, 2-0, 3-4]     -> false
         4 edges, but 0-1-2 is a loop and {3, 4} is cut off

Graph C: n = 4, edges = [0-1, 2-3]               -> false
         no loop, but two separate pieces
Three small graphs, made up for this page

Graph B is the instructive one. It has the right number of edges for a tree on five nodes, yet it fails twice: a triangle uses up one edge too many in one place, which leaves the other place one edge short. That pattern is general. With exactly n - 1 edges, a loop somewhere always means a gap somewhere else, so checking connectivity alone is enough.

Ask before you code: can the list contain the same edge twice, or an edge from a node to itself? Should zero nodes count as a tree? Is node labeling always 0 to n - 1? The duplicate question matters most, because it breaks one popular shortcut, explained below.

Why it shows up in interviews

Graph Valid Tree is short, but it rewards knowing what a tree actually is in graph terms rather than in the parent-and-children sense from binary tree problems. Candidates who recall the edge-count fact finish in a few minutes and then get pushed on why it is true. Candidates who do not recall it can still pass by checking loops and connectivity separately. Either way, the interviewer is listening for a precise definition and for how duplicates and self-loops are handled.

The facts that make it easy

For a graph with n nodes, any two of these imply the third
PropertyWhy it matters here
ConnectedEvery node can reach every other node, so there is at least one route between any pair.
No loops (acyclic)There is at most one route between any pair.
Exactly n - 1 edgesA connected graph needs at least n - 1 edges, and a loop-free one can have at most n - 1.
For a graph with n nodes, any two of these imply the third. Scroll sideways on a small screen.

The middle row of reasoning is worth having ready. Start with n separate nodes, which is n pieces. Each edge you add either joins two different pieces, reducing the count by one, or lands inside a piece and creates a loop. To get from n pieces down to one you need n - 1 joining edges. So with exactly n - 1 edges, connected means no edge was wasted on a loop, and loop-free means every edge did a join and you end with one piece.

A slower first approach

A direct translation of the definition: add the edges one at a time, and before adding each, run a search over the edges added so far to see whether its two endpoints are already connected. If they are, this edge closes a loop. After all edges, run one more search to make sure everything is reachable. Each check costs up to O(V + E), so the whole thing is O(E × (V + E)). It works, and it shows you understand the definition, but it repeats a search for every edge.

A common alternative is a depth-first search that skips the node it came from and reports a loop when it sees any other visited neighbor. On a clean edge list that is fine. On a list that repeats an edge, skipping by node label hides the second copy, so a doubled edge is not reported as a loop. If the input can contain duplicates, check the edge count first, or skip the parent by edge index instead of by node.

from collections import deque


def valid_tree(n, edges):
    if len(edges) != n - 1:
        return False
    nbrs = [[] for _ in range(n)]
    for a, b in edges:
        nbrs[a].append(b)
        nbrs[b].append(a)
    reached = {0}
    frontier = deque([0])
    while frontier:
        node = frontier.popleft()
        for other in nbrs[node]:
            if other not in reached:
                reached.add(other)
                frontier.append(other)
    return len(reached) == n
Python: edge count plus breadth-first search from node 0. O(V + E) time and space.

This version is robust to messy input. A duplicated edge or a self-loop still counts toward the n - 1 total but adds no new reach, so the search comes up short and the function returns false, which is correct because both create a loop. With n = 0 it returns false, since the edge count would have to be minus one; if the interviewer wants an empty graph to count as a tree, add that as a special case.

Optimal approach 2: union-find

Give each node a leader, initially itself. For each edge, find the leaders of both endpoints. If they match, the two nodes are already linked and this edge would close a loop, so return false. Otherwise make one leader point to the other. If the edge count was n - 1 and every edge performed a merge, the n starting pieces have become exactly one, so the graph is connected and the answer is true.

function validTree(n, edges) {
  if (edges.length !== n - 1) return false;
  const leader = Array.from({ length: n }, (_, i) => i);
  const find = (x) => {
    while (leader[x] !== x) {
      leader[x] = leader[leader[x]];
      x = leader[x];
    }
    return x;
  };
  for (const [a, b] of edges) {
    const ra = find(a);
    const rb = find(b);
    if (ra === rb) return false; // this edge would close a loop
    leader[ra] = rb;
  }
  return true;
}
JavaScript: union-find with path halving. Fails on the first edge that joins two already-linked nodes.

Union-find is the better fit when edges arrive as a stream, because it never needs the whole adjacency list. The breadth-first search is easier to write from memory and has a cleaner bound. If you want the near-constant time per operation that union-find is known for, merge by size or rank as well as halving paths; this snippet halves paths only, which is fast in practice but does not carry that formal guarantee.

Complexity summary

V nodes and E edges
ApproachTimeExtra space
Search before adding each edgeO(E × (V + E))O(V + E)
Edge count, then BFSO(V + E)O(V + E)
Edge count, then union-find with path halvingO(V + E log V) worst case, near linear in practiceO(V)
Union-find with halving and union by sizeO((V + E) α(V)), effectively linearO(V)
V nodes and E edges. Scroll sideways on a small screen.

Edge cases to try

  • One node and no edges: a tree.
  • One node with an edge to itself: not a tree, and the edge count already says so.
  • Two nodes joined by the same edge twice, plus a third isolated node: n - 1 edges, but not a tree.
  • A path of n nodes: a tree, and the deepest possible search.
  • A star with one center: a tree with the widest possible frontier.
  • The right edge count but two pieces, one of which has a loop.

Mistakes to avoid

  • Checking only that there are no loops, which accepts a forest of several separate trees.
  • Checking only that there are n - 1 edges, which accepts a triangle plus a stranded pair.
  • Adding each undirected edge to one adjacency list instead of both.
  • Skipping the parent by node label in a DFS when the input may repeat edges.
  • Starting the search from node 0 without first handling n = 0.

Follow-ups

  • Return the edge that breaks the tree. If the graph is a tree plus one extra edge, union-find returns it directly; that is Redundant Connection.
  • How many edges are missing? Count the separate pieces and subtract one. Counting pieces is the whole of Number of Connected Components.
  • The edges are directed. Is it a rooted tree? Exactly one node has no incoming edge, every other node has exactly one, and everything is reachable from that root.
  • Which node makes the shortest tree when used as the root? Strip leaves layer by layer from the outside in; the one or two nodes left at the end are the centers.

How to explain it out loud

Fictional example

Justifying the edge-count shortcut
Candidate
A tree on n nodes is connected with no loops, and it always has n - 1 edges. So I will return false right away if the count is wrong.
Interviewer
Why is the count enough together with connectivity?
Candidate
Think of n separate pieces. Every edge either joins two pieces or makes a loop inside one. Reaching a single piece takes n - 1 joins. If I have exactly n - 1 edges and end up connected, none of them can have been spent on a loop.
Candidate
Then one breadth-first search from node 0 should reach all n nodes. That is linear in nodes plus edges, and it also handles repeated edges, since a repeat adds to the count without adding any reach.

Number of Connected Components uses the same union-find but keeps going instead of stopping at the first loop. Redundant Connection assumes the graph is almost a tree and asks which edge to drop. For loops in directed graphs the right tool is different; see Course Schedule II. Grid-shaped graphs are covered in Number of Islands, and the coding problems hub lists every walkthrough.

Where Natively helps

This problem is mostly about saying the definition precisely. In a practice session on Mac or Windows, Natively can read the prompt from a screenshot and lay out an approach, such as the edge-count check followed by a search, with a reminder about duplicate edges. It also transcribes a mock interview, which makes it easy to see later whether your explanation of the n - 1 rule held together. See the AI interview assistant for more.

Questions people ask

How do you check if a graph is a valid tree?

Return false unless there are exactly n - 1 edges, then run one BFS or DFS from any node and confirm it reaches all n nodes. With that edge count, connected implies no cycles. It runs in O(V + E).

Why does a tree with n nodes have n - 1 edges?

Start with n separate nodes. Each edge either joins two separate pieces or creates a loop inside one, and a tree has no loops, so it takes exactly n - 1 joins to end with one piece.

Can you solve Graph Valid Tree with union-find?

Yes. Merge the endpoints of each edge and return false if an edge joins two nodes that already share a leader. With exactly n - 1 edges and no such edge, everything ends in one set.

What about duplicate edges or self-loops?

Both count as loops, so the graph is not a tree. The edge count plus connectivity check rejects them automatically; a DFS that skips its parent by node label can miss a repeated edge.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP